簡體   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