我得到一个类似的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
}
}
我尝试使用Gson定义java类来解析这个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的源字符串。但我可以忽略&#34;计数&#34;属性,因为我知道它的大小为Map<String, CarSize> cars
。
答案 0 :(得分:1)
您的Cars
对象似乎有一个Car List<Car>
和count property
列表。
麻烦的是,count属性在地图中。我做的是扩展地图,只是为了添加属性。然后,您需要为此映射定义自己的序列化器/反序列化器 (来源get-nested-json-object-with-gson)
模特:
class Cars {
private MyMap cars = new MyMap();
public MyMap getCars() {
return cars;
}
public void setCars(MyMap cars) {
this.cars = cars;
}
public void add(String name, Car car){
cars.put(name, car);
cars.setCount(cars.getCount()+1);
}
}
class MyMap extends HashMap<String, Car> {
private int count;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
class Car {
private int length;
private int weight;
public Car() {
}
public Car(int length, int weight) {
this.length = length;
this.weight = weight;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
}
自定义Serializer / Deserializer:
class MyDeserializer implements JsonDeserializer<MyMap>
{
@Override
public MyMap deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
JsonElement count = json.getAsJsonObject().remove("count");
MyMap myMap = new Gson().fromJson(json.getAsJsonObject().toString(), type);
if(count!=null){
myMap.setCount(count.getAsInt());
}
return myMap;
}
}
class MySerializer implements JsonSerializer<MyMap>
{
@Override
public JsonElement serialize(MyMap src, Type type, JsonSerializationContext context) {
JsonElement serialize = context.serialize(src, Map.class);
serialize.getAsJsonObject().add("count", new JsonPrimitive(src.getCount()));
return serialize;
}
}
读取和写入json的代码:
String json = "{\"cars\":{\"jeep\":{\"length\":4670,\"weight\":1450},\"ford\":{\"length\":4460,\"weight\":1880},\"count\":128}}";
Cars cars = new Cars();
cars.add("jeep", new Car(4670, 1450));
cars.add("ford", new Car(4460, 1880));
Gson gson = new GsonBuilder()
.registerTypeAdapter(MyMap.class, new MyDeserializer())
.registerTypeAdapter(MyMap.class, new MySerializer())
.create();
String json2 = gson.toJson(cars);
cars = gson.fromJson(json, Cars.class);
cars = gson.fromJson(json2, Cars.class);