我有一个特定形式的 json,我必须反序列化。为了做到这一点,我想到了我最好的库 Gson,但我在这里遇到了一个问题,因为我有一些动态的密钥。
我想你会通过一个很好的例子来理解。这是json:
{
"institution1": {
"_id": "51cc7bdc544ddb3f94000002",
"announce": { },
"city": "Melun",
"coordinates": [
2.65106,
48.528976
],
"country": "France",
"created_at": "2013-06-27T17:52:28Z",
"name": "italien",
"state": "Seine et Marne",
"street": "Avenue Albert Moreau",
"updated_at": "2013-06-27T17:52:28Z"
},
"institution2": {
"_id": "51d1dfa8544ddb9157000001",
"announce": {
"announce1": {
"_id": "51d1e036544ddb9157000002",
"created_at": "2013-07-01T20:02:35Z",
"description": "description formule 1",
"institution_id": "51d1dfa8544ddb9157000001",
"title": "formule dejeune",
"type": "restoration",
"updated_at": "2013-07-01T20:02:35Z"
},
"announce2": {
"_id": "51d1e074544ddb9157000003",
"created_at": "2013-07-01T20:03:08Z",
"description": "description formule soir",
"institution_id": "51d1dfa8544ddb9157000001",
"title": "formule soiree",
"type": "restoration",
"updated_at": "2013-07-01T20:03:08Z"
}
},
"city": "Melun",
"coordinates": [
2.65106,
48.528976
],
"country": "France",
"created_at": "2013-07-01T19:59:36Z",
"name": "restaurant francais chez pierre",
"state": "Seine et Marne",
"street": "Avenue Albert Moreau",
"updated_at": "2013-07-01T19:59:36Z"
}
}
你可以去这里看更好的风景。所以,我创建了一个类来做到这一点,JsonModel.java
public class JsonModel
{
public HashMap<String, Institution> entries;
public static class Institution
{
public String _id;
public HashMap<String, Announce> announce;
public String city;
public String country;
public List<Double> coordinates;
public String created_at;
public String name;
public String state;
public String street;
public String updated_at;
}
public static class Announce
{
public String _id;
public String created_at;
public String description;
public String institution_id;
public String title;
public String type;
public String updated_at;
}
}
然后,我要求 Gson 使用以下代码对其进行反序列化:
JsonModel data = new Gson().fromJson(json, JsonModel.class);
由于数据为空,我认为它没有按我预期的方式工作......我考虑过使用 HashMap,因为我事先不知道机构 1、机构 2 等密钥......你怎么看?我可以这样做吗?
请不要告诉我使用支架,我只是梦想拥有那些!
先感谢您 !
编辑: 我能够通过添加一个根对象来使这个东西工作
{
"root":{ ..the json.. }
}
和改变
public HashMap<String, Institution> entries;
经过
public HashMap<String, Institution> root;
所以,问题是 gson 需要识别第一个元素,但实际上我将无法修改 json,有没有办法让它以不同的方式完成?