매우 기본적인 문제가 있습니다. 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}"
는 내가 잘못된 방법으로이 변환을하고있는 중이 야 생각합니다. 그것을하기위한 제안 된 방법은 무엇입니까? 예를 들어
나는 그것을 얻지 못한다. 무엇이 문제인가? –
Gson은 일치하는 필드를 설정합니다 (해당되는 경우 없음 포함). – Bohemian