1
我得到一个JSON字符串这样的:如何定义类来解析这个使用Gson的JSON?
{
"cars": {
"ford": {
"length": 4460,
"weight": 1450
},
"jeep": {
"length": 4670,
"weight": 1880
},
"toyota": {
"length": 3830,
"weight": 1120
},
.
.
.
"audi": {
"length": 5288,
"weight": 2432
},
"subaru": {
"length": 4755,
"weight": 1790
},
"count": 128
}
}
我尝试定义的Java类分析使用GSON这个JSON。
public class CarSize {
public int length;
public int weight;
}
public class JSONData {
public Map<String, CarSize> cars;
}
问题是cars
是不是一个纯地图,它具有"count":128
和128
不是CarSize
。我如何解析JSON?
请注意我无法修改JSON的源字符串。但我可以忽略“count”属性,因为我知道这是Map<String, CarSize> cars
的大小。
谢谢Alex。但我正在使用Gson。 Gson没有'ObjectMapper'。 –
我的不好!但它仍然激起了如何定义模型的问题。我会用Gson更新它 – alexbt
对于Gson,您可以使用: Gson gson = new Gson();汽车汽车= gson.fromJson(json,Cars.class); // json是你的json字符串 –