2015-01-14 49 views
0

我有一个具有多个Web模块的Java Web应用程序。一个将充当服务器,其他模块充当客户端,两者都部署在不同的服务器上。客户端应用程序将通过休息服务调用服务器应用程序来获取和保存数据从服务器我得到一个JSON字符串,我试图将它转换为与泛型类型的对象。杰克逊与泛型JSON无法构建java.lang.Class的实例

这是我的目标

public class MyObject<T> { 

    private String name; 
    private List<T> list; 

    private final Class<T> referenceType; 

    @JsonCreator 
    public MyObject(@JsonProperty("referenceType") Class<T> referenceType) { 
     this.referenceType = referenceType; 
     list = new ArrayList<T>(); 
    } 

    public Class<T> getReferenceType() { 
     return this.referenceType; 
    } 

//getter and setter 
} 

在服务器,我设置对象在以下方式

public String getAll(Long key) { 
    List<SomeObject> list = someObjectDao.getAll(key); 
    MyObject<SomeObject> myObject = new MyObject<SomeObject>(
        SomeObject.class); 
    appObject.setList(list); 
    JSONObject jsonget = new JSONObject(myObject); 
    return jsonget.toString(); 
} 

在客户端应用程序,我得到的JSON字符串这样

{"name":"someName","referenceType":"class com.pkg.model.SomeObject","list":[{list - index - 0},{list - index-1}]} 

而我试图将字符串转换为MyObject类型如下方式

private MyObject readJson(String output) throws Exception { 
     return new ObjectMapper().readValue(output, 
        new TypeReference<MyObject>() { 
        }); 
    } 

但我发现了以下情况例外,

Can not construct instance of java.lang.Class, problem: class com.pkg.model.SomeObject 
at [Source: [email protected]; line: 1, column: 151] 

我如何转换的JSON字符串到对象?

谢谢。

回答

1

你的客户端就OK了,你正在阅读的JSON是无效

以下将反序列化正确

"referenceType":"com.pkg.model.SomeObject" 

比你用列表的一部分被卡住。

设置服务器端使用jackson,例如

return new ObjectMapper().writeValueAsString(myObject); 

将解决您的问题