解析为JSON错误:无法调用no-args构造函数

时间:2016-03-28 15:00:31

标签: java json gson

我有以下类,我想序列化为JSON,然后作为对象返回:

public class CustomerKeys2 {

    protected JAXBElement<String> customerIdPub;

    //getter & setter
}

我的序列化/反序列化代码就像这样

CustomerKeys2 customerKeys = new CustomerKeys2();
//getJaxbString just get a JAXBElement<String> from a regular String
customerKeys.setCustomerIdPub(getJaxbString("CustomerIdPub"));
Gson gson = new Gson();
String jsonString = gson.toJson(customerKeys);
CustomerKeys2 obj2 = gson.fromJson(jsonString, CustomerKeys2.class);

最后一行(gson.fromJson)抛出错误:

java.lang.RuntimeException: Unable to invoke no-args constructor for java.lang.Class<java.lang.String>. Register an InstanceCreator with Gson for this type may fix this problem.

这是因为customerIdPub是JAXBElement类型而不仅仅是常规String。 问题是我无法修改CustomerKeys2类。它是外部JAR的一部分,我必须使用它。

我已经尝试过其他库(flexjson,Jackson ......)但是同样的错误。

有解决方法吗?

0 个答案:

没有答案