如何使用 Gson 将 JSON 转换为 HashMap? [英] How can I convert JSON to a HashMap using Gson?
本文介绍了如何使用 Gson 将 JSON 转换为 HashMap?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在从以 JSON 格式返回数据的服务器请求数据.在发出请求时将 HashMap 转换为 JSON 一点也不难,但另一种方式似乎有点棘手.JSON 响应如下所示:
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"
}
哪种方式最容易访问这些数据?我正在使用 GSON 模块.
What way would be easiest to access this data? I'm using the GSON module.
推荐答案
给你:
import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson("{'k1':'apple','k2':'orange'}", type);
这篇关于如何使用 Gson 将 JSON 转换为 HashMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文