2017-04-21 1 views
1

알 수없는 JSON 값 ... 자바 잭슨 : 난 아직도 잭슨을 사용하는 방법을 배우고

그래서 가끔 정수, 긴 문자열, 또는 목록

을하는 값을 갖는 JSON 개체가

값 : 정수

{ 
    "id":1, 
    "active":1, 
    "name":"name1", 
    "value":155, 
    ... 

값 : 문자열

{ 
    "id":2, 
    "active":1, 
    "name":"name2", 
    "value":"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book...", 
    ... 

값 : 목록

01 여기 23,516,
{ 
    "id":3, 
    "active":1, 
    "name":"name3", 
    "value":[ 
    "One", 
    "Two", 
    "Three", 
    "Four"], 
    ... 

그래서 모두 함께 모습 ...

{ 
    { 
     "id":1, 
     "active":1, 
     "name":"name1", 
     "value":155, 
     ... 
    }, 
    { 
     "id":2, 
     "active":1, 
     "name":"name2", 
     "value":"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book...", 
     ... 
    }, 
    { 
     "id":3, 
     "active":1, 
     "name":"name3", 
     "value":[ 
     "One", 
     "Two", 
     "Three", 
     "Four"], 
     ... 
    } 
} 

내 POJO 모델

@JsonIgnoreProperties(ignoreUnknown=true) 
@JsonAutoDetect(fieldVisibility= JsonAutoDetect.Visibility.ANY) 
public class OQScoresRows { 
    private int id; 
    private int active; 
    private String name; 
    private List<String> value; 
    ... ... 

는 여기에 내가 실행할 때 문제는 내 매퍼 코드

ObjectMapper mapper = new ObjectMapper(); 
try{ 
    POJO obj = mapper.readValue(<JSONOBJECT>, POJO.class); 
}catch(JsonParseException e){ 
    return mapper.writeValueAsString(e); 
} 

입니다 내 코드, 다음과 같은 오류가 발생합니다 :

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of VALUE_NUMBER_INT token 

그것은 "값이"세 가지 유형 중 하나를 포함 할 수 있기 때문에 이것이 내가 유형을 수용 할 수있을만큼 내 코드를 유연하게 어떻게, 무슨 일이 일어나고 나에게 분명 ... 난 항상 다른 방법의 경우 검색 할 수 있습니다 값은 int, List 또는 String입니다. 그러나 먼저 모델링해야합니다. (예 ...)

내 질문은 간단합니다. 유형을 수용 할 수있을만큼 코드를 유연하게 만드는 방법 ...

+0

목록 을 사용하고 역 직렬화 중에 목록에 요소가 하나 이상 포함되어 있는지 확인하십시오. 요소가 하나만 포함되어 있으면 long 또는 int로 분석하십시오. 실패하면 String입니다. 물론, 좋은 접근 방식이 아니며 아마도 1 값 필드 대신 4를 가져야하고 역 직렬화 중에 jsonignoreproperties를 사용해야합니다. – opensam

+0

먼저 배열을 단일 값으로 처리해야하며, ObjectMapper를 구성하면됩니다. ''int'를'String'으로 다루고 싶다면, 주석으로 처리 할 수 ​​있습니다 : '@JsonDeserialize (using = StringDeserializer.class, as = String). 클래스) 개인 목록 값; ' – nazlo

답변

3

Integer, ListString 중 하나 일 수 있으면 Object으로 신고하고 나중에로 전송할 수 있습니다.예 :

if(value instanceof Integer){ 
    //do something after casting it to Integer 
}else if(value instanceof List){ 
    //do something after casting it to List 
}else if(value instanceof String){ 
    do something after casting it to String 
} 
+0

좋아 - 그렇게 나에게 반 감각을 만든다 ...나중에 "그것을 비 변환해라"는 것은 무엇을 의미합니까? 언제 나중에 발생합니까? 죄송합니다. 코드를 요청하는 것이 적절한 에티켓이 아니라는 것을 알고 있지만, 나중에 "정확히"의미하는 것을 이해하려고합니다. –

+0

그래, 그렇다면 어떤 부분이 의미가 없습니까? –

+0

@DidierJeanCharles 답변을 –

1

If-else 문이 질문에 대한 괜찮지 만, 당신 때문에, JSON 오브젝트의 모든 문자열 형식의 :

@JsonIgnoreProperties(ignoreUnknown=true) 
@JsonAutoDetect(fieldVisibility= JsonAutoDetect.Visibility.ANY) 
public class OQScoresRows { 
    private int id; 
    private int active; 
    private String name; 
    private Object value; 

는 deserializeing, 후에는 다음과 같은 논리를 쓸 수 있습니다 값에서 데이터 유형을 식별하는 방법을 찾아야합니다. 예를 들어, 식별 int에 Integer.valueOf(value); 신원 명부에 [로 시작하십시오; 다른 하나는 문자열 유형입니다. json 문자열을 객체 또는 목록으로 변환하는 일반적인 방법 인 this answer을 참조 할 수 있습니다.