简体   繁体   English

如何将 json 字符串反序列化为不同的特定 java 对象?

[英]how to deserialize json string to different specific java Object?

I managed to serialize an extreme complex class (which nests 50-some customize java object) to json string using gson.我设法使用 Z6071660820906DE 将一个极其复杂的 class(其中嵌套了 50 个自定义 java 对象)序列化为 json 字符串。 Here is a piece of my object:这是我的一块 object:

public class myComplexObject{
     private int a;
     private String b;
     private myclassA c;
     private myclassB d;
     ...
     private map<String, Object> x;
}

please note the field private map<String, Object> x , the VALUE Object could be Integer , Double , String , myClassC ,... it works well when serializing, but when deserializing, gson could not convert the json string as my expectation. please note the field private map<String, Object> x , the VALUE Object could be Integer , Double , String , myClassC ,... it works well when serializing, but when deserializing, gson could not convert the json string as my expectation. eg for the json string例如对于 json 字符串

{
"keyA":"1",
}

I expect that gson could convert it to Integer , but gson recognize it as Double .Which will lead exception in later process.我希望 gson 可以将其转换为Integer ,但 gson 将其识别为Double 。这将在以后的过程中导致异常。

So, my question is, what should I do to let the serializer(not limited to gson) know that when deserializing a json string to a java Object class like this, which should be convert to Integer , which should be convert to Double ... So, my question is, what should I do to let the serializer(not limited to gson) know that when deserializing a json string to a java Object class like this, which should be convert to Integer , which should be convert to Double .. .

When deserializing a JSON number with Gson as Object , it defaults to deserializing the JSON value as Java Double (as you have seen). When deserializing a JSON number with Gson as Object , it defaults to deserializing the JSON value as Java Double (as you have seen). Recently in Gson 2.8.9 a new feature has been added which allows specifying a ToNumberStrategy .最近在 Gson 2.8.9 中添加了一个允许指定ToNumberStrategy的新功能。 This allows you to more easily influence how Gson deserializes JSON numbers.这使您可以更轻松地影响 Gson 如何反序列化 JSON 数字。 Some default implementations are provided by the ToNumberPolicy enum. ToNumberPolicy枚举提供了一些默认实现。 The one closest to your requirement is ToNumberPolicy.LONG_OR_DOUBLE .最接近您的要求的是ToNumberPolicy.LONG_OR_DOUBLE If you really need Integer as value type, you can try writing your own implementation similar to Gson's one .如果您确实需要Integer作为值类型,您可以尝试编写自己的实现,类似于Gson 的实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM