简体   繁体   English

使用Gson反序列化Map <String,Object>字段

[英]Deserializing a Map<String, Object> field with Gson

I have a User object with this structure: 我有一个具有这种结构的User对象:

class User {
    private String id;
    private String name;
    private Map<String, Object> properties;

    // GETTERS & SETTERS
}

I have a JSON String with this structure: 我有一个具有这种结构的JSON字符串:

{
    "user": {
        "id:"123456789",
        "name:"azerty",
        "emailHash":"123456789", // not used in User class
        "properties": {
            "p1":1,
            "p2":"test",
            "p3":[1, 2, 3, 4],
            "p4":{
               etc...
            }
        }
    }
}

Properties' keys are String, Properties' values can be a String, int, Array, boolean, Map etc. 属性的键是String,属性的值可以是String,int,Array,boolean,Map等。

I try to deserialize this JSON string with Gson like that: 我尝试用Gson反序列化这个JSON字符串:

JsonParser parser = new JsonParser();
JsonElement element = parser.parse(jsonString);
JsonObject object = element.getAsJsonObject();

GsonBuilder builder = new GsonBuilder();
builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
Gson gson = builder.create();
User user = (User) gson.fromJson(object.get("user"), new TypeToken<User>() {}.getType());

Fields 'id' and 'name' are correctly injected but the field 'properties' stays null. 字段'id'和'name'被正确注入,但字段'properties'保持为null。

Do you know what I'm doing wrong? 你知道我做错了什么吗? Thanks in advance for your help! 在此先感谢您的帮助!

For me this code: 对我来说这段代码:

public class Main {
    public static void main(String[] args) throws IOException {
    GsonBuilder builder = new GsonBuilder();
    builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
    Gson gson = builder.create();
    FileInputStream inputStream = new FileInputStream(new File("bobi.json"));
    InputStreamReader reader = new InputStreamReader(inputStream);
    User user = gson.fromJson(reader, User.class);
    System.out.println(user.getName());
    System.out.println(user.getId());
    for (String property : user.getProperties().keySet()) {
        System.out.println("Key: " + property + " value: " + user.getProperties().get(property));
    }
    reader.close();
}

Prints this: 打印这个:

azerty
123456789
Key: p1 value: 1.0
Key: p2 value: test
Key: p3 value: [1.0, 2.0, 3.0, 4.0]
Key: p4 value: {}

However, keep in mind that I have stripped the wrapping json object in the file I parse. 但是,请记住,我已经解析了我解析的文件中的包装json对象。 The file is: 该文件是:

{
        "id":"123456789",
        "name" : "azerty",
        "emailHash":"123456789", 
        "properties": {
            "p1":1,
            "p2":"test",
            "p3":[1, 2, 3, 4],
            "p4":{

            }
        }
}

Also I added closing double quote for name and id , which you did not have in your sample. 另外,我添加了关于nameid结束双引号,你在样本中没有。

The User class as requested by the OP. OP请求的User类。 I have added getters and setters for the reason of printing: 我为打印原因添加了getter和setter:

import java.util.Map;

class User {
    private String id;
    private String name;
    private Map<String, Object> properties;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Map<String, Object> getProperties() {
        return properties;
    }
    public void setProperties(Map<String, Object> properties) {
        this.properties = properties;
    }
}

错误的反序列化列表<object>与 gson<div id="text_translate"><p> 我用List&lt;Object&gt;调试CUSTOMER object:</p><p> <a href="https://i.stack.imgur.com/Gh2Mx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Gh2Mx.png" alt="在此处输入图像描述"></a></p><p> 这是 CUSTOMER.class:</p><pre> public class CUSTOMER { @XmlElements({ @XmlElement(name = "ADDRESS", type = ADDRESS.class), @XmlElement(name = "ZIP", type = ZIP.class), @XmlElement(name = "CITY", type = CITY.class), @XmlElement(name = "COUNTRY", type = COUNTRY.class), }) protected List&lt;Object&gt; addressAndZIPAndCITY; // other fields }</pre><p> 但是当我反序列化并从中创建 json 时,它仅包含:</p><pre> { "addressAndZIPAndCITY": [ { "value": "some value", "type": "some type" }, { "value": "some value 2", "type": "some type 2" }] }</pre><p> 缺少 ADRESS、ZIP、CITY 和 COUNTRY 对象标题。 所以反序列化不好。</p><p> 我无法更改List&lt;Object&gt;声明。 是否可以选择将其反序列化为带有 ADRESS、ZIP、CITY 等的 json? 像这样:</p><pre> { "addressAndZIPAndCITY": [{ "ADDRESS": { "value": "some value", "type": "some type" } }, { "ZIP": { "value": "some value 2", "type": "some type 2" } } ] }</pre><p> 编辑:我的意思是它看起来像 GSON 不知道哪个 object 在那里,但可能你知道如何向 model 添加一些注释或其他东西来识别它?</p></div></object> - Wrong deserializing List<Object> with gson

暂无
暂无

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

相关问题 使用GSON将JSON对象反序列化为字符串字段 - Deserializing JSON object to string field with GSON 反序列化地图 <Object, Object> 与GSon - Deserializing Map<Object, Object> with GSon 使用 Gson 反序列化映射键需要一个对象 - Deserializing map key with Gson expects an object gson 将字段反序列化为 null - gson deserializing a field as null 格森地图 <String, Any> 反对 - Gson Map<String, Any> to Object 使用Gson反序列化对象时,字段异常的值无效 - Invalid value for field exception while deserializing object using Gson Gson通过改变字段类型进行反序列化 - Gson deserializing with changing field types Gson 读数无法解析 object Map 字段 - Gson reading cannot resolve object Map field Java:将JSON结构反序列化为Map <String, Object> - Java: Deserializing JSON structure to Map<String, Object> 错误的反序列化列表<object>与 gson<div id="text_translate"><p> 我用List&lt;Object&gt;调试CUSTOMER object:</p><p> <a href="https://i.stack.imgur.com/Gh2Mx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Gh2Mx.png" alt="在此处输入图像描述"></a></p><p> 这是 CUSTOMER.class:</p><pre> public class CUSTOMER { @XmlElements({ @XmlElement(name = "ADDRESS", type = ADDRESS.class), @XmlElement(name = "ZIP", type = ZIP.class), @XmlElement(name = "CITY", type = CITY.class), @XmlElement(name = "COUNTRY", type = COUNTRY.class), }) protected List&lt;Object&gt; addressAndZIPAndCITY; // other fields }</pre><p> 但是当我反序列化并从中创建 json 时,它仅包含:</p><pre> { "addressAndZIPAndCITY": [ { "value": "some value", "type": "some type" }, { "value": "some value 2", "type": "some type 2" }] }</pre><p> 缺少 ADRESS、ZIP、CITY 和 COUNTRY 对象标题。 所以反序列化不好。</p><p> 我无法更改List&lt;Object&gt;声明。 是否可以选择将其反序列化为带有 ADRESS、ZIP、CITY 等的 json? 像这样:</p><pre> { "addressAndZIPAndCITY": [{ "ADDRESS": { "value": "some value", "type": "some type" } }, { "ZIP": { "value": "some value 2", "type": "some type 2" } } ] }</pre><p> 编辑:我的意思是它看起来像 GSON 不知道哪个 object 在那里,但可能你知道如何向 model 添加一些注释或其他东西来识别它?</p></div></object> - Wrong deserializing List<Object> with gson
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM