2014-09-18 3 views
0

매우 기본적인 문제가 있습니다. json 문자열을 객체로 변환해야합니다. 해당 클래스로 변환 할 것으로 예상되는 예외를 throw 할 수있는 사용자 지정 메서드가 아래에있는 개체를 가져올 수없는 경우.json string에 대한 일반 getObject() 메소드를 작성하는 방법은 무엇입니까?

protected <T> T getObjectFromJson(Class<T> c, String json){ 
    try{ 
     Gson gson = new Gson(); 
     T object = gson.fromJson(json, c); 
     return object; 
    } catch (Exception e){ 
     throw new TMMIDClassConversionException(e.getCause(), e.getMessage()); 
    } 
} 

다른 클래스의 json을 변환하려고하면이 메서드는 예외를 throw하지 않습니다.

내 클래스

public class CompanyCategoryMap { 

private Integer id; 
private int mid; 
private String catKey; 
private String catValue; 
private int priority; 

public Integer getId() { 
    return id; 
} 

public void setId(Integer id) { 
    this.id = id; 
} 

public int getMid() { 
    return mid; 
} 

public void setMid(int mid) { 
    this.mid = mid; 
} 

public String getCatKey() { 
    return catKey; 
} 

public void setCatKey(String catKey) { 
    this.catKey = catKey; 
} 

public String getCatValue() { 
    return catValue; 
} 

public void setCatValue(String catValue) { 
    this.catValue = catValue; 
} 

public int getPriority() { 
    return priority; 
} 

public void setPriority(int priority) { 
    this.priority = priority; 
} 

}

내가 JSON의 Company의 문자열이 아니라 위 클래스의 문자열을 전달하면 예외가 발생하지 않습니다.

문자열 :

"{\"id\":6,\"name\":\"abc\",\"usersCount\":10,\"mid\":3,\"createdAt\":\"Sep 15, 2014 7:02:19 PM\",\"updatedAt\":\"Sep 15, 2014 7:02:19 PM\",\"active\":true,\"currency\":\"abc\",\"source\":\"unknown\",\"user_id\":1,\"tierId\":1}" 

는 내가 잘못된 방법으로이 변환을하고있는 중이 야 생각합니다. 그것을하기위한 제안 된 방법은 무엇입니까? 예를 들어

+1

나는 그것을 얻지 못한다. 무엇이 문제인가? –

+0

Gson은 일치하는 필드를 설정합니다 (해당되는 경우 없음 포함). – Bohemian

답변

1

테이크 :

class Foo { 
    private String value; 
} 

class Bar { 
    private String value; 
} 

하고

String json = "{\"value\" : \"whatever\"}"; 
new Gson().fromJson(json, Foo.class); 
new Gson().fromJson(json, Bar.class); 

왜 GSON이 중 하나를 거부해야 하는가?

Gson은 지정된 JSON을 지정한대로 Class의 인스턴스로 역 직렬화하기 위해 최선의 노력을 다하고 있습니다. 발견 한만큼 필드를 맵핑합니다. 아무 것도 발견되지 않으면, 그것은 너무 나쁩니다.

잭슨 (Jackson)과 같은 다른 도서관은 그 반대입니다. 기본적으로 Jackson은 주어진 모든 클래스 속성에 대한 매핑을 포함하지 않는 JSON을 거부합니다. 일부 속성을 무시하도록 구성 할 수도 있습니다.

계속 작업하고 계십시오. 응용 프로그램 작성자 인 경우 Class 인스턴스를 적절한 JSON 소스와 함께 사용해야하는시기를 알아야합니다.

+0

그것을 얻었습니다! 여기 잭슨을 사용해야 할 것입니다. 엄격한 변환이 필요합니다. –

관련 문제