[英]Json string to HashMap can not deserialize
{"Messages":[{"KEY01":"VALUE01"}, {"KEY02":"VALUE02"}, {"KEY03":"VALUE03"}]}
This is my json string. 这是我的json字符串。 Im trying to map it to hashmap. 我试图将其映射到hashmap。 This is what im doing: 这就是我在做什么:
messageByLanguage = mapper.readValue(jsonString, MessageByLanguage.class);
This my MessageByLanguage class: 这是我的MessageByLanguage类:
public class MessageByLanguage {
@JsonProperty("Messages")
private Map<String, String> messages = new HashMap<String, String>();
public MessageByLanguage (){};
public void setMessages(Map<String, String> messages) {
this.messages = messages;
}
public Map<String, String> getMessages() {
return messages;
}
can not deserialize instance of java util linkedhashmap out of start_array token
Thats what error I get. 那是我得到的错误。 Can someone tell me what i'm doing wrong? 有人能告诉我我做错了什么吗?
Try Google Gson 试试Google Gson
For Following Json 跟随Json
String json="{\"Messages\":[{\"KEY01\":\"VALUE01\"}, {\"KEY02\":\"VALUE02\"}, {\"KEY03\":\"VALUE03\"}]}";
You need to Modify your parsing in this way 您需要以这种方式修改解析
Gson gson=new Gson();
Map<String,Map<String,String>> map=new HashMap<String,Map<String,String>>();
map=(Map<String,Map<String,String>>) gson.fromJson(json, map.getClass());
System.out.println(map.keySet());
System.out.println(map.values());
Now Output 现在输出
[Messages] //Key in String
[[{KEY01=VALUE01}, {KEY02=VALUE02}, {KEY03=VALUE03}]] // Value in Map<String,String>
Now to Get the acutal set of keys and values for Messages 现在来获取消息的一组关键和值
Iterate this way 这样迭代
for(Map.Entry<String,Map<String,String>>entry:map.entrySet()){
ArrayList<Map<String,String>>list=(ArrayList<Map<String, String>>) entry.getValue();
for(Map<String,String>innerMap:list){
System.out.print(innerMap.keySet()+"\t");
System.out.println(innerMap.values());
}
}
Your final Output 你的最终输出
[KEY01] [VALUE01]
[KEY02] [VALUE02]
[KEY03] [VALUE03]
The problem is that your input is a map from a string to an array, and that array is a collection of objects, each of which has a single key->value (at least in your example). 问题是您的输入是从字符串到数组的映射,该数组是对象的集合,每个对象都有一个key-> value(至少在您的示例中)。
If you really need a map of those key->value pairs, then you will need to: 如果您确实需要这些key->值对的映射,那么您将需要:
Map<String,List<Map<String,String>>>
, although you could also create an object that handles some of this. 如果你真的想把它作为一个单独的对象,那么它就是一个Map<String,List<Map<String,String>>>
,尽管你也可以创建一个处理其中一些对象的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.