2016-07-15 2 views
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 
    } 
} 

내가 GSON를 사용하여이 JSON을 구문 분석하는 자바 클래스를 정의하려고합니다.

public class CarSize { 
    public int length; 
    public int weight; 
} 

public class JSONData { 
    public Map<String, CarSize> cars; 
} 

문제는 cars 그것은 "count":128을 가지고 있으며, 128CarSize 아닌, 순수한지도되지이다. JSON을 어떻게 파싱 할 수 있습니까?

JSON 소스 문자열을 수정할 수 없습니다. 그러나 나는 그것이 "Map<String, CarSize> cars"의 크기라는 것을 알고 있기 때문에 "count"속성을 무시하는 것이 좋습니다.

답변

1

Cars 개체에는 자동차 List<Car>count property 목록이있는 것 같습니다.

문제는 count 속성이지도에 있음을 의미합니다. 내가 한 것은지도를 확장하여 속성을 추가하는 것입니다.

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; 
    } 
} 

코드 읽기 :

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; 
    } 
} 

사용자 정의 시리얼 라이저/디시리얼라이저 : 그럼, 당신이지도 (출처 get-nested-json-object-with-gson)

모델에 대한 자신의 시리얼 라이저/디시리얼라이저를 정의 할 필요가 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);   
+0

Alex. 감사합니다. 하지만 저는 Gson을 사용하고 있습니다. Gson에는'ObjectMapper '가 없습니다. –

+0

내 잘못! 그러나 당신의 모델이 어떻게 정의되어야하는지에 관해서는 여전히 의문이 남아 있습니다. Gson으로 업데이트합니다. – alexbt

+0

Gson의 경우 다음을 사용할 수 있습니다. Gson gson = new Gson(); 자동차 cars = gson.fromJson (json, Cars.class); // json은 json 문자열입니다. –

관련 문제