如何为json字符串编写一个通用的getObject()方法



遇到了一个非常基本的问题。我必须将json字符串转换为对象。我有一个自定义方法,如下所示,它被期望转换成相应的类,如果无法从中获取对象,则抛出异常

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,这个方法不会抛出异常。

我的班级

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;
}

}

当我传递Company的json字符串而不是上面类的string时,它不会抛出异常。

字符串:

"{"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}"

我认为我做这种转换的方式不对。建议的方法是什么?

以为例

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拒绝任何不包含每个给定类属性映射的JSON。您也可以将其配置为忽略某些属性。

继续做你正在做的事情。作为应用程序编写者,您应该知道何时使用具有适当JSON源的Class实例。