小编典典

如何使用Gson将JSON转换为HashMap?

json

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

{ 
    "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模块。


阅读 601

收藏
2020-07-27

共1个答案

小编典典

干得好:

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);
2020-07-27