2017-09-04 14 views
-2

私のサーバーからこのJSONを受け取っています。私の要求は、通常のユースケースとは少し異なります。私の場合、私は@Embeddedを部屋のライブラリから提供しています。ルーム組み込みクラスへの改造を使用したJSONの逆シリアル化

[ 
{ 
    "id": 105, 
    "title": "Clear notification", 
    "message": "Opening the app should automatically clear the notifications", 
    "klass": "Demo", 
    "priority": 0, 
    "timestamp": "2017-09-03T07:20:56.130500Z", 
    "teacher": "ABC", 
    "attachments": [] 
}, 
{ 
    "id": 104, 
    "title": "Attachment", 
    "message": "File upload take 1", 
    "attachments": [ 
     { 
      "id": 5, 
      "name": "Technology List.txt", 
      "url": "https://cdn.filestackcontent.com/", 
      "type": "text/plain", 
      "size": 954 
     } 
    ] 
} 

]

POJOの上記のJSONのために。 JSONをFeedWithAttachmentクラスにデシリアライズしています。

public class FeedWithAttachment { 
    @NotNull @Embedded 
    public Feed feed; 
    @Relation(parentColumn = "id", entityColumn = "feedId", entity = Attachment.class)  
    public List<Attachment> attachments; 

} 

マイFeedクラス:

data class Feed(
     @PrimaryKey @SerializedName("id") 
     var id: Long = 0, 

     @SerializedName("title") 
     var title: String = "", 

     @SerializedName("message") 
     var message: String = "", 
) 

私のアタッチメントクラス:

data class Attachment(
     @PrimaryKey @SerializedName("id") 
     var attachmentId: Int = 0, 
     var name: String = "", 
     var url: String = "", 
     var type: String = "", 
     var size: Long = 0, 
     @Transient 
     var feedId: Long = 0 
) 

我々はFeedモデルでList<Attachmentを入れた場合は、予想通り、それは動作します。残念ながら私の要求は、FeedWithAttachmentという別のクラスが必要なものです。

改修:

interface FeedService { 
    public Call<List<FeedWithAttachment>> getFeeds(); 
} 

問題

私はfeednullで、attachmentsが期待される応答にFeedWithAttachmentを取得しています。

+0

あなたは、このクラスを使うのか?あなたの答えを投稿してください。 –

+0

@MehulKabaria 'FeedWithAttachment'は' feed'が 'null'で、' attachments'は期待どおりです。 –

+0

同じJavaクラスを使用して、サーバーの応答とデータベース構造を表現しようとしているようです。これらのことは完全に独立しています。サーバーは提供されたJSONの性質を変更することができ、データベースのリレーショナル構造(RoomがサポートするSQLite機能の特定のサブセット)に限定されます。 IMHO、将来同じクラスを使う必要がないので、同じクラスを使うのは面倒ではありません。サーバーの応答とデータベース構造をモデル化した別のクラスを用意してください。 – CommonsWare

答えて

0

FeedWithAttachmentにフィード変数を書き込むときは、jsonのキーで「フィード」を検索してください。 クラスに定義されている各変数名は、jsonのキーに存在する必要があります。

public class FeedWithAttachment { 
    int id; 
    String title; 
    String message; 
    String klass; 
    int priority; 
    String timestamp; 
    String teacher; 

    List<Attachment> attachments; 
} 

とAttachment.class::API呼び出しの応答であなたは何をしたか

public class Attachment{ 
    int id; 
    String name; 
    String url; 
    String type; 
    int size; 
} 
+0

私はこの解決策を知っています。しかし、私たちは 'FeedWithAttachment'に' Feed'を埋め込むことができます –

+0

@AkshayChordiya私が知る限り、それは不可能です。 –

+0

よろしいですか。私は他のいくつかの回避策を試みます。ありがとう –

関連する問題