繁体   English   中英

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

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

我设法使用 Z6071660820906DE 将一个极其复杂的 class(其中嵌套了 50 个自定义 java 对象)序列化为 json 字符串。 这是我的一块 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. 例如对于 json 字符串

{
"keyA":"1",
}

我希望 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 .. .

When deserializing a JSON number with Gson as Object , it defaults to deserializing the JSON value as Java Double (as you have seen). 最近在 Gson 2.8.9 中添加了一个允许指定ToNumberStrategy的新功能。 这使您可以更轻松地影响 Gson 如何反序列化 JSON 数字。 ToNumberPolicy枚举提供了一些默认实现。 最接近您的要求的是ToNumberPolicy.LONG_OR_DOUBLE 如果您确实需要Integer作为值类型,您可以尝试编写自己的实现,类似于Gson 的实现。

暂无
暂无

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

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