如何使用Gson将JSON转换为HashMap? [英] How can I convert JSON to a HashMap using Gson?

查看:2004
本文介绍了如何使用Gson将JSON转换为HashMap?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从以JSON格式返回数据的服务器请求数据。在发出请求时将HashMap转换为JSON并不难,但另一方面似乎有点棘手。 JSON响应如下所示:

  {
header:{
alerts:[
{
AlertID:2,
TSExpires:null,
目标:1,
文本 ,
Type:1
},
{
AlertID:3,
TSExpires:null,
目标:1,
文本:woot,
类型:1
}
],
会话 0bc8d0835f93ac3ebbf11560b2c5be9a
},
result:4be26bc400d3c
}

访问这些数据最简单的方法是什么?我正在使用GSON模块。

解决方案

你去哪里

  Type type = new TypeToken< Map< String,String>>(){}。getType(); 
映射< String,String> myMap = gson.fromJson({'k1':'apple','k2':'orange'},type);


I'm requesting data from a server which returns data in the JSON format. Casting a HashMap into JSON when making the request wasn't hard at all but the other way seems to be a little tricky. The JSON response looks like this:

{ 
    "header" : { 
        "alerts" : [ 
            {
                "AlertID" : "2",
                "TSExpires" : null,
                "Target" : "1",
                "Text" : "woot",
                "Type" : "1"
            },
            { 
                "AlertID" : "3",
                "TSExpires" : null,
                "Target" : "1",
                "Text" : "woot",
                "Type" : "1"
            }
        ],
        "session" : "0bc8d0835f93ac3ebbf11560b2c5be9a"
    },
    "result" : "4be26bc400d3c"
}

What way would be easiest to access this data? I'm using the GSON module.

解决方案

Here you go

Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson("{'k1':'apple','k2':'orange'}", type);

这篇关于如何使用Gson将JSON转换为HashMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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