【问题标题】:java - Convert JSONObject to HashMap<String, String>java - 将 JSONObject 转换为 HashMap<String, String>
【发布时间】:2019-02-03 16:25:11
【问题描述】:

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

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

【问题讨论】:

  • 重复问题这里已经给出了解决方案solution
  • 这不是我想要的@Himly

标签: java android json hashmap


【解决方案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); 
}

【讨论】:

  • 但我需要将其转换为 HashMap 而不是 HashMap
【解决方案2】:

试试这样的:

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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-17
    • 2017-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多