我从我的服务器接收此JSON。我的要求与通常的用例略有不同,因此这个问题。就我而言,我使用了Room库提供的@Embedded
。
[
{
"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
}
]
}
上述JSON的POJO。我将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
)
如果我们将List<Attachment
放在Feed
模型中,那么它会按预期工作。不幸的是,我的要求是需要另一个名为FeedWithAttachment
的类。
改造:
interface FeedService {
public Call<List<FeedWithAttachment>> getFeeds();
}
问题
我在FeedWithAttachment
为feed
且null
符合预期的回复中获得attachments
。
答案 0 :(得分:0)
在FeedWithAttachment中编写Feed变量时,请尝试查找&#34; feed&#34;在json的钥匙。 类中定义的每个变量名必须存在于json的键中。 你使用这个类:
public class FeedWithAttachment {
int id;
String title;
String message;
String klass;
int priority;
String timestamp;
String teacher;
List<Attachment> attachments;
}
和Attachment.class:
public class Attachment{
int id;
String name;
String url;
String type;
int size;
}