我有一个结构如下的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
字符串的结构
有没有办法弄到这样的东西?谢谢你的帮助。
发布于 2018-08-29 09:41:21
您可以使用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);
}
发布于 2018-08-29 11:25:35
尝试如下所示:
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);
}
https://stackoverflow.com/questions/52067981
复制相似问题