猿问

java - 将 JSONObject 转换为 HashMap<String, String>

我有一个JSONObject这样的结构:


"data": {

   "title": "Pool Party",

   "date": {

       "start": "2018-08-14T15:44:44.625Z",

       "end": "2018-08-14T18:44:44.625Z"

}

我想把它转换成


HashMap<String, String>

对于“日期”字段下的“开始”和“结束”字段,有没有一种方法可以以相同的方式构建地图?


我尝试使用Gson如下方式转换它:


Type type = new TypeToken<Map<String, String>>(){}.getType();

HashMap<String, String> params = Gson().fromJson(jsonString, type);

但我收到了这个错误:


com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT

可能是因为我的JSON字符串的结构


有没有办法得到这样的东西?谢谢您的帮助。


米琪卡哇伊
浏览 337回答 2
2回答

智慧大石

您可以使用 ObjectMapper 来转换它。public void testJackson() throws IOException {&nbsp;&nbsp;&nbsp; &nbsp; ObjectMapper mapper = new ObjectMapper();&nbsp;&nbsp; &nbsp; String json = "{"data": {"title": "Pool Party","date": {"start": "2018-08-14T15:44:44.625Z", "end": "2018-08-14T18:44:44.625Z"}}}";&nbsp;&nbsp; &nbsp; TypeReference<HashMap<String,Object>> typeRef&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; = new TypeReference<HashMap<String,Object>>() {};&nbsp; &nbsp; HashMap<String,Object> o = mapper.readValue(from, typeRef);&nbsp;&nbsp; &nbsp; System.out.println("Got " + o);&nbsp;}

LEATH

尝试这样的事情:public void testJackson() throws IOException {&nbsp; &nbsp; ObjectMapper mapper = new ObjectMapper();&nbsp; &nbsp; String json = "{\"data\": {\"title\": \"Pool Party\",\"date\": {\"start\":\"2018-08-14T15:44:44.625Z\", \"end\":\"2018-08-14T18:44:44.625Z\"}}}";&nbsp; &nbsp; TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {&nbsp; &nbsp; };&nbsp; &nbsp; HashMap<String, Object> o = mapper.readValue(from, typeRef);&nbsp; &nbsp; System.out.println("Got " + o);}
随时随地看视频慕课网APP

相关分类

Java
我要回答