java-将JSONObject转换为HashMap <string,string =“”>

时间:2018-08-29 00:45:55

标签: java android json hashmap

我有一个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字符串的结构

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

2 个答案:

答案 0 :(得分:1)

您可以使用ObjectMapper对其进行转换。

public void testJackson() throws IOException {  
    ObjectMapper mapper = new ObjectMapper(); 
    String json = "{"data": {"title": "Pool Party","date": {"start": "2018-08-14T15:44:44.625Z", "end": "2018-08-14T18:44:44.625Z"}}}"; 
    TypeReference<HashMap<String,Object>> typeRef 
            = new TypeReference<HashMap<String,Object>>() {};

    HashMap<String,Object> o = mapper.readValue(from, typeRef); 
    System.out.println("Got " + o); 
}

答案 1 :(得分:0)

尝试这样的事情:

public void testJackson() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    String json = "{\"data\": {\"title\": \"Pool Party\",\"date\": {\"start\":\"2018-08-14T15:44:44.625Z\", \"end\":\"2018-08-14T18:44:44.625Z\"}}}";
    TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {
    };
    HashMap<String, Object> o = mapper.readValue(from, typeRef);
    System.out.println("Got " + o);
}