2014-09-03 5 views
0

구문 분석 할 JSON 문서가 아래와 같습니다. files 배열에 두 개의 개체 만 표시하고 있습니다. 일반적으로 나는 500 개가 넘는 물건을 가지고있을 것입니다. 나는 모든 new_usersname 경우 태그가 /testing01을 가지고 추출하고 자바 HashSet에서 그것을 채울 필요가GSON을 사용하여 JSON 배열을 Java 객체에 직렬화하는 방법은 무엇입니까?

public class JsonResponseTest { 
    private String name; 
    private String max_chain_entries; 
    private String partition; 
    private String new_users; 

    // getters here 
} 

-

{ 
    "files":[ 
     { 
     "name":"/testing01/partition_395.shard", 
     "max_chain_entries":20, 
     "partition":"297, 298", 
     "new_users":"123, 345, 12356" 
     }, 
     { 
     "name":"/testing02/partition_791.shard", 
     "max_chain_entries":20, 
     "partition":"693, 694, 695", 
     "new_users":"3345, 6678, 34568" 
     } 
    ] 
} 

그리고 여기에 위의 객체에 대한 내 DataModel이 클래스입니다. JSON 직렬화에 GSON을 사용하고 있습니다.

private static RestTemplate restTemplate = new RestTemplate(); 
private static final Gson gson = new Gson(); 

public static void main(String[] args) { 

    String jsonResponse = restTemplate.getForObject(
      "some_url", String.class); 

    Type collectionType = new TypeToken<List<JsonResponseTest>>() {}.getType(); 
    List<JsonResponseTest> navigation = gson.fromJson(jsonResponse, collectionType); 

    System.out.println(navigation); 
} 

그러나 위의 코드는 다음과 같이 나에게 오류 메시지를주고있다 - 내가 여기서 뭐하는 거지 잘못된

Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $ 

아무것도?

+4

문제는 JSON 배열이 없다는 것입니다. 값이 JSON 배열 인 "files"속성이있는 (단일) JSON 객체가 있습니다. 그리고 코드는 원시 JSON 배열을 기다리고 있습니다. –

+1

사소한 포인트 : JSON 문자열이 "serialize"됩니다. 사용중인 언어에 대한 내부 표현으로 변환하려면 "비 직렬화"하십시오. JSON 문자열로 다시 변환하려면 "serialize"하십시오. –

+0

JSON 구문을 배우려면 json.org를 방문하십시오. 배우는 데 5-10 분 밖에 걸리지 않으며 다음 번에 너 자신을 당황하게하지 않도록 도와줍니다. –

답변

2

문제는 JSON 개체가 먼저 있고 JSON 배열이 있지만 JSON 배열이라고 생각하는 것이 비 직렬화됩니다. 아래 코드를 시도하십시오 -

String jsonResponse = restTemplate.getForObject("some_url", String.class); 

Type collectionType = new TypeToken<List<JsonResponseTest>>() {}.getType(); 

JsonObject json = new JsonParser().parse(jsonResponse).getAsJsonObject(); 
JsonArray jarr = json.getAsJsonObject().getAsJsonArray("files"); 

List<JsonResponseTest> navigation = gson.fromJson(jarr, collectionType); 
System.out.println(navigation); 
관련 문제