如何反序列化Map< String,Object>进入POJO? [英] How to deserialize a Map<String, Object> into POJO?

查看:287
本文介绍了如何反序列化Map< String,Object>进入POJO?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Map< String,Object>,其中包含反序列化形式的JSON.我想将其反序列化到POJO的字段中.

I have a Map<String, Object> which contains a deserialized form of JSON. I would like to deserialize this into the fields of a POJO.

我可以使用Gson来执行此操作,方法是将Map序列化为JSON字符串,然后将JSON字符串反序列化为POJO,但这效率不高(请参见下面的示例).没有中间步骤怎么办?

I can perform this using Gson by serializing the Map into a JSON string and then deserializing the JSON string into the POJO, but this is inefficient (see example below). How can I perform this without the middle step?

该解决方案最好使用Gson或Jackson,因为该项目已在使用它们.

The solution should preferably use either Gson or Jackson, as they're already in use by the project.

示例代码:

import java.util.HashMap;
import java.util.Map;

import com.google.gson.Gson;

public class Test {
    public static void main(String[] args) {
        Map<String, Object> innermap = new HashMap<String, Object>();
        innermap.put("number", 234);
        innermap.put("string", "bar");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("number", 123);
        map.put("string", "foo");
        map.put("pojo2", innermap);

        Gson gson = new Gson();

        // How to perform this without JSON serialization?
        String json = gson.toJson(map);
        MyPojo pojo = gson.fromJson(json, MyPojo.class);

        System.out.println(pojo);
    }
}


class MyPojo {
    private int number;
    private String string;
    private MyPojo pojo2;

    @Override
    public String toString() {
        return "MyPojo[number=" + number + ", string=" + string + ", pojo2=" + pojo2 + "]";
    }
}

推荐答案

使用Gson,您可以将Map转换为JsonElement,然后可以使用fromJson完全相同的方式对其进行解析:

Using Gson, you can turn your Map into a JsonElement, which you can then parse in exactly the same way using fromJson:

JsonElement jsonElement = gson.toJsonTree(map);
MyPojo pojo = gson.fromJson(jsonElement, MyPojo.class);

这类似于您已经在使用的toJson方法,除了它避免编写JSON String表示形式,然后在将其转换为类之前避免将JSON String解析回JsonElement.

This is similar to the toJson method that you are already using, except that it avoids writing the JSON String representation and then parsing that JSON String back into a JsonElement before converting it to your class.

这篇关于如何反序列化Map&lt; String,Object&gt;进入POJO?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆