【问题标题】:Convert JSON to HashMap using XStream使用 XStream 将 JSON 转换为 HashMap
【发布时间】:2014-04-15 21:55:29
【问题描述】:

我有一个地图形式的 JSON 字符串:

{ “露西”:{ “身份证”:456, "full_name": "GOOBER, ANGELA", "user_id": "2733245678", “斯汀”:“2733212346” }, “迈拉”:{ “身份证”:123, "full_name": "鲍勃,史蒂夫", "user_id": "abc213", “斯汀”:“9040923411” } }

我想将其转换为 HashMap,键为“Lucy”、“Myra”等,值为 JavaObject

Class Person
{
String id;
String fullName;
String userId;
Strring stin;

}

我该怎么做?我有点暗示我需要使用 MapConverter,但是关于如何使用的文档很少。我使用 XStream 创建了列表(使用 addImplicitCollection),但不知道 Map。

【问题讨论】:

    标签: java json hashmap converter xstream


    【解决方案1】:

    你也可以用“jackson”来做到这一点

    ObjectMapper objMapper = new ObjectMapper();
    Map<String, Person> mpCards =  objMapper.readValue(strJSONString, new TypeReference<Map<String, Person>>(){});
    

    【讨论】:

    • 感谢我最终使用了 Jackson,因为无法弄清楚如何为此使用 XStream。我想知道你是否知道如何在使用 Jackson 解析时忽略节点
    • 忽略节点的意思是,你想跳过你的 Person 类中的一些属性?可以详细告诉我吗?
    【解决方案2】:

    将 JSON 转换为地图地图。遍历外部映射,获取映射条目的值(内部映射),并将其传递给您的对象的构造函数,该构造函数接受映射并构造相应的对象。用指向构造对象的指针替换指向内部映射的指针。 (为了让 Java 泛型满意,您可能需要创建一个新映射而不是更新旧映射。)

    伪代码(几乎可以在任何地方):

    Map<String, Map> theWholeThing = myJSONParser.parseJSONIntoObject(theWholeJSONString);
    Map<String, Person> theNewThing = new HashMap<String, Person>();
    // Use your favorite Map iterating style -- I picked this at random
    for (Map.Entry<String, String> entry : theWholeThing.entrySet()) {
        String key = entry.getKey();
        Map<String, String> value = entry.getValue();
        Person person = new Person(value);
        theNewThing.put(key, person);
    }
    return theNewThing;
    

    在类人:

    Person(Map<String, String) map) {
        this.id = map.get("id");
        this.fullName = map.get("full_name");
        this.userId = map.get("user_id");
        this.stin = map.get("stin");
    }
    

    如果您愿意,可以在 Person 上创建 FromJsonMap 静态工厂方法,而不是使其成为构造函数。

    【讨论】:

    • 您能否用示例代码详细说明一下。我无法修改 JSON 结构(无法控制它!)。
    猜你喜欢
    • 1970-01-01
    • 2011-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-07
    相关资源
    最近更新 更多