[java] JsonMappingException : START_ARRAY 토큰에서 벗어남

다음 .json 파일이 제공됩니다.

[
    {
        "name" : "New York",
        "number" : "732921",
        "center" : [
                "latitude" : 38.895111,
                "longitude" : -77.036667
            ]
    },
    {
        "name" : "San Francisco",
        "number" : "298732",
        "center" : [
                "latitude" : 37.783333,
                "longitude" : -122.416667
            ]
    }
]

포함 된 데이터를 표현하기 위해 두 개의 클래스를 준비했습니다.

public class Location {
    public String name;
    public int number;
    public GeoPoint center;
}

public class GeoPoint {
    public double latitude;
    public double longitude;
}

.json 파일의 내용을 구문 분석하기 위해 Jackson 2.2.x를 사용 하고 다음 방법을 준비했습니다.

public static List<Location> getLocations(InputStream inputStream) {
    ObjectMapper objectMapper = new ObjectMapper();
    try {
        TypeFactory typeFactory = objectMapper.getTypeFactory();
        CollectionType collectionType = typeFactory.constructCollectionType(
                                            List.class, Location.class);
        return objectMapper.readValue(inputStream, collectionType);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

center속성을 생략하는 한 모든 콘텐츠를 구문 분석 할 수 있습니다. 그러나 지리 좌표를 구문 분석하려고하면 다음 오류 메시지가 표시됩니다.

com.fasterxml.jackson.databind.JsonMappingException :
[출처 : android.content.res.AssetManager$AssetInputStream@416a5850; 줄 : 5, 열 : 25]
(참조 체인을 통해 : com.example.Location [ “center”])



답변

JSON 문자열 형식이 잘못되었습니다.의 유형 center은 잘못된 개체의 배열입니다. 교체 []함께 {}주변의 JSON 문자열 longitudelatitude그들이 개체 수 있도록 :

[
    {
        "name" : "New York",
        "number" : "732921",
        "center" : {
                "latitude" : 38.895111,
                "longitude" : -77.036667
            }
    },
    {
        "name" : "San Francisco",
        "number" : "298732",
        "center" : {
                "latitude" : 37.783333,
                "longitude" : -122.416667
            }
    }
]


답변

JsonMappingException: out of START_ARRAY token예외는 응답에서를 Object {}찾은 반면 잭슨 객체 매퍼에 의해 발생합니다 Array [{}].

이 문제 ObjectObject[]에 대한 인수에서 로 대체 하여 해결할 수 있습니다 geForObject("url",Object[].class). 참조 :

  1. 참고 1
  2. 참고 2
  3. 참고 3

답변

이 문제는 JSONLint.com에서 json을 확인한 다음 수정하는 것으로 분류했습니다. 그리고 이것은 동일한 코드입니다.

String jsonStr = "[{\r\n" + "\"name\":\"New York\",\r\n" + "\"number\": \"732921\",\r\n"+ "\"center\": {\r\n" + "\"latitude\": 38.895111,\r\n"  + " \"longitude\": -77.036667\r\n" + "}\r\n" + "},\r\n" + " {\r\n"+ "\"name\": \"San Francisco\",\r\n" +\"number\":\"298732\",\r\n"+ "\"center\": {\r\n" + "    \"latitude\": 37.783333,\r\n"+ "\"longitude\": -122.416667\r\n" + "}\r\n" + "}\r\n" + "]";

ObjectMapper mapper = new ObjectMapper();
MyPojo[] jsonObj = mapper.readValue(jsonStr, MyPojo[].class);

for (MyPojo itr : jsonObj) {
    System.out.println("Val of name is: " + itr.getName());
    System.out.println("Val of number is: " + itr.getNumber());
    System.out.println("Val of latitude is: " +
        itr.getCenter().getLatitude());
    System.out.println("Val of longitude is: " +
        itr.getCenter().getLongitude() + "\n");
}

참고 : MyPojo[].classjson 속성의 getter 및 setter가있는 클래스입니다.

결과:

Val of name is: New York
Val of number is: 732921
Val of latitude is: 38.895111
Val of longitude is: -77.036667
Val of name is: San Francisco
Val of number is: 298732
Val of latitude is: 37.783333
Val of longitude is: -122.416667


답변

말했듯 JsonMappingException: out of START_ARRAY token이 Jackson 객체 매퍼는를 예상하고 응답을 Object {}찾은 반면 예외는 예외입니다 Array [{}].

더 간단한 해결책은 방법 getLocations을 다음 으로 대체하는 것 입니다.

public static List<Location> getLocations(InputStream inputStream) {
    ObjectMapper objectMapper = new ObjectMapper();
    try {
        TypeReference<List<Location>> typeReference = new TypeReference<>() {};
        return objectMapper.readValue(inputStream, typeReference);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

반면에와 같은 pojo가 없으면 Location다음을 사용할 수 있습니다.

TypeReference<List<Map<String, Object>>> typeReference = new TypeReference<>() {};
return objectMapper.readValue(inputStream, typeReference);


답변