2011-04-26 4 views
18

그래서 GSON을 사용하여 API에서 JSON을 구문 분석하고 데이터의 동적 필드를 구문 분석하는 방법에 대해 고민하고 있습니다. 여기 동적 JSON 필드를 GSON으로 구문 분석하는 방법은 무엇입니까?

쿼리에 반환 된 JSON 데이터의 예는 다음과 같습니다

{ 

- 
30655845: { 
    id: "30655845" 
    name: "testdata 
    description: "" 
    latitude: "38" 
    longitude: "-122" 
    altitude: "0" 
    thumbnailURL: http://someimage.com/url.jpg 
    distance: 9566.6344386665 
} 
- 
28688744: { 
    id: "28688744" 
    name: "testdata2" 
    description: "" 
    latitude: "38" 
    longitude: "-122" 
    altitude: "0" 
    thumbnailURL: http://someimage.com/url.jpg 
    distance: 9563.8328713012 
} 
} 

나는 현재 단일 정적 값을 처리하고 방법은 클래스입니다 :

import com.google.gson.annotations.SerializedName; 

public class Result 
{ 
@SerializedName("id") 
public int id; 

@SerializedName("name") 
public String name; 

@SerializedName("description") 
public String description; 

@SerializedName("latitude") 
public Double latitude; 

@SerializedName("longitude") 
public Double longitude; 

@SerializedName("altitude") 
public Double altitude; 

@SerializedName("thumbnailURL") 
public String thumbnailURL; 

@SerializedName("distance") 
public Double distance; 
} 

을 그리고 내가 할 수있는 다음 구문을 사용하여 GSON을 사용하면됩니다.

Gson gson = new Gson(); 

Reader reader = new InputStreamReader(source); 

Result response= gson.fromJson(reader, Result.class); 

내가 쿼리하고 얻을 수있는 것처럼이 데이터가 서브 데이터에서 작동한다는 것을 알고 있습니다. 단일 항목 및 매우 쉽게 구문 분석 할 수 있지만 배열의 각 값에 대해 주어진 임의의 정수 값은 어떻습니까? (예 : 30655845 및 2868874)

도움이 필요하십니까?

답변

19

GSON documentation에 따르면 당신은 같은 일을 수행 할 수 있습니다

Type mapType = new TypeToken<Map<Integer, Result> >() {}.getType(); // define generic type 
Map<Integer, Result> result= gson.fromJson(new InputStreamReader(source), mapType); 

또는 당신은 당신의 클래스에 대한 custom serializer를 작성하려고 할 수 있습니다.

면책 조항 : GSon과 관련한 경험이 없지만 Jackson과 같은 다른 프레임 워크에 대해서는 경험이 없습니다.

+1

완벽하게 작동했습니다. 정말 고마워. : D –

+0

NewtonSoft를 사용하여 동일하게 구문 분석 할 수있는 방법이 있습니까? –

관련 문제