我想用外部JSon文件填充Java类,我和Gson Builder一起工作。但是我的Java类不会被我在JSon文件中声明的值填充。问题是什么?谢谢你的帮助!
这是我的Json文件:
{
"tstamp": "2012-11-21 18:00",
"id": 123,
"publicationList": [
{
"id": "1L",
"state": "PublicationState.IMMEDIATELY",
"channel": "PublicationChannel.TIMETABLE",
"startDate": "2001-12-17 18:00",
"endDate": "2001-12-17 18:00"
},
{
"id": "2L",
"state": "PublicationState.IMMEDIATELY",
"channel": "PublicationChannel.NVS",
"startDate": "2001-12-17 18:00",
"endDate": "2001-12-17 18:00"
},
{
"id": "3L",
"state": "PublicationState.IMMEDIATELY",
"channel": "PublicationChannel.NVS",
"startDate": "2001-12-17 18:00",
"endDate": "2001-12-17 18:00"
}
]
}
这是我的Gson Builder和GSon Instance Creator:
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd HH:mm")
.registerTypeAdapter(Publication.class,
new PublicationInstanceCreator()).create();
public class PublicationInstanceCreator implements
InstanceCreator<PublicationDto> {
@Override
public PublicationDto createInstance(Type type) {
return new PublicationDto();
}
}
这是Java Class PublicattionDto:
public class PublicationDto{
private static final long serialVersionUID = 1L;
private Long id;
private PublicationState state = PublicationState.IMMEDIATELY;
private PublicationChannel channel;
private Date startDate;
private Date endDate;
//getter and setter methods
}
答案 0 :(得分:0)
你的错误是什么?您的代码中也缺少主要的POJO对象。
假设此对象为Publications
,则只需使用
Publications p = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm").create().fromJson(json, Publications.class);
您的适配器无效。另外我认为带有“L”的ID也不会起作用(放下L),GSon会将数字转换为正确的Long类型。