0
{"Messages":[{"KEY01":"VALUE01"}, {"KEY02":"VALUE02"}, {"KEY03":"VALUE03"}]}

This is my json string. Im trying to map it to hashmap. This is what im doing:

messageByLanguage = mapper.readValue(jsonString, MessageByLanguage.class);

This my MessageByLanguage class:

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?

  • have you tried this? http://stackoverflow.com/questions/4392326/issue-when-trying-to-use-jackson-in-java – melc Feb 20 '15 at 07:47

2 Answers2

0

Try Google Gson

For Following 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]
Neeraj Jain
  • 7,643
  • 6
  • 34
  • 62
0

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).

If you really need a map of those key->value pairs, then you will need to:

  1. read in the entire object. If you really want to do this as a single object, it is a Map<String,List<Map<String,String>>>, although you could also create an object that handles some of this.
  2. convert the array to a map. You'll need to write the code for this yourself, but it means iterating through the list and taking the key,value pair from the map and putting it into a new Map.
Prisoner
  • 49,922
  • 7
  • 53
  • 105