2012-06-05 1 views
4

Google GSON을 사용하여 Java 개체를 JSON으로 변환합니다.GSON : 필드를 상위 개체로 이동하는 방법

현재 나는 다음과 같은 구조를 갖는 해요 :

"Step": { 
    "start_name": "Start", 
    "end_name": "End", 
    "data": { 
    "duration": { 
     "value": 292, 
     "text": "4 min." 
    }, 
    "distance": { 
     "value": 1009.0, 
     "text": "1 km" 
    }, 
    "location": { 
     "lat": 59.0000, 
     "lng": 9.0000, 
     "alt": 0.0 
    } 
    } 
} 

현재 Duration 객체는 Data 객체 안에 있습니다. 나는이처럼 Data 객체를 생략하고 Step 객체에 Duration 개체를 이동하고 싶습니다 :

나는이 사용 GSON을 할 수있는 방법
"Step": { 
    "start_name": "Start", 
    "end_name": "End", 
    "duration": { 
    "value": 292, 
    "text": "4 min." 
    }, 
    "distance": { 
    "value": 1009.0, 
    "text": "1 km" 
    }, 
    "location": { 
    "lat": 59.0000, 
    "lng": 9.0000, 
    "alt": 0.0 
    } 
} 

?

편집 : Type.Adapter를 사용하여 Step.class를 수정하려고 시도했지만 쓰기 메소드에서 JsonWriter에 내 기간 객체를 추가 할 수 없습니다.

답변

3

당신은 아마이 작업을 수행 할 수 있습니다 Data 대신 Duration 등으로 작업하십시오.

// registering your custom serializer: 
GsonBuilder builder = new GsonBuilder(); 
builder.registerTypeAdapter (Step.class, new StepSerializer()); 
Gson gson = builder.create(); 
// now use 'gson' to do all the work 

아래의 사용자 지정 시리얼 라이저에 대한 코드는 머리 꼭대기에서 쓰고 있습니다. 예외 처리를 수행하지 못하고 컴파일되지 않을 수 있으며 Gson의 인스턴스를 반복적으로 만드는 것과 같은 작업을 반복합니다. 난 단지`serialize`, 그래서`deserialize`이 중요하지 않는 것입니다 필요

class StepSerializer implements JsonSerializer<Step> 
{ 
    public JsonElement serialize (Step src, 
           Type typeOfSrc, 
           JsonSerializationContext context) 
    { 
     Gson gson = new Gson(); 
     /* Whenever Step is serialized, 
     serialize the contained Data correctly. */ 
     JsonObject step = new JsonObject(); 
     step.add ("start_name", gson.toJsonTree (src.start_name); 
     step.add ("end_name", gson.toJsonTree (src.end_name); 

     /* Notice how I'm digging 2 levels deep into 'data.' but adding 
     JSON elements 1 level deep into 'step' itself. */ 
     step.add ("duration", gson.toJsonTree (src.data.duration); 
     step.add ("distance", gson.toJsonTree (src.data.distance); 
     step.add ("location", gson.toJsonTree (src.data.location); 

     return step; 
    } 
} 
+0

:하지만 당신이 원하는 것 물건의 종류를 나타냅니다. 위는 단지 나의 구조의 한 예일뿐입니다. 실제로 내 데이터 객체에는'toJsonTree'에 포함될 필요가있는 추가 필드가 들어 있습니다. 어떻게 내가 그걸 할 수 있는지? – dhrm

+0

이 * 정말로 * 의존합니다. 두 개의 추가 입력란이있는 예를 표시하면 내가 생각할 수있는 내용이 표시됩니다. 주의 사항 : 내 답변은 Gson 설명서를 기반으로합니다. 나는 전에 이런 이상한 일을 한 적이 없어. – ArjunShankar

+0

데이터 오브젝트 내부의 추가 필드로 내 질문을 업데이트했습니다. – dhrm

0

나는 gson에서 그것을 할 beautifull 방법이 있다고 생각하지 않습니다. 어쩌면, 데이터를 제거 기간을두고 JSON으로 직렬화, 초기 JSON에서 자바 객체 (지도)를 얻을 : 쓰기, 다음 custom serializerStep에 등록하고, 그 안에 확인하여

Map initial = gson.fromJson(initialJson); 

// Replace data with duration in this map 
Map converted = ... 

String convertedJson = gson.toJson(converted); 
관련 문제