0

I have a JSON like this: [{key:key1, value:value1}, {key:key2, value:value2}, ..., {key:keyn, value:valuen}]

and I need a HashMap in Java from that json like: {key1:value1, key2:value2, ..., keyn:valuen}

Is there a simple way to have it converted like this? I'm trying with Jackson but don't know how to specify key and value keywords.

Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
Julia
  • 1

3 Answers3

0

It is very simple: https://stackoverflow.com/a/24012023/7137584

I would recommend using Jackson library:

import com.fasterxml.jackson.databind.ObjectMapper;

TypeReference<HashMap<String, Object>> typeRef = new TypeReference<>() {};
Map<String, Object> mapping = new ObjectMapper().readValue(jsonStr, typeRef);
  • This code fails for the given input with this exception: ``Exception in thread "main" com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.HashMap` out of START_ARRAY token`` – Nowhere Man Sep 08 '21 at 10:18
0

The input JSON describes an array/list of map entries where each entry is a POJO:

@Data
class Entry {
    private String key;
    private String value; // the type of value may be Object
}

Here @Data is a Lombok annotation which provides getters, setters, toString, etc.

So, at first a list of map entries is read, which is converted then to the map:

String json = "[{\"key\":\"key1\", \"value\":\"value1\"}, {\"key\":\"key2\", \"value\":\"value2\"}, {\"key\":\"keyN\", \"value\":\"valueN\"}]";

// step 1: read raw list of entries
List<Entry> input = mapper.readValue(json, new TypeReference<List<Entry>>() {});

// step 2: convert to map
Map<String, String> mapRead = input.stream()
       .collect(Collectors.toMap(Entry::getKey, Entry::getValue));

System.out.println(mapRead);

Output:

{key1=value1, key2=value2, keyN=valueN}
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
0

Here's a solution using the JSON-P api.

import javax.json.*;

var str = "[{\"key\":\"key1\", \"value\":\"value1\"}, {\"key\":\"key2\", \"value\":\"value2\"}, {\"key\":\"keyN\", \"value\":\"valueN\"}]";
JsonReader reader = Json.createReader(new StringReader(str));
JsonArray jarr = reader.readArray();
Map<String,String> map = new HashMap<>();
for(JsonValue jv : jarr) {
    JsonObject jo = (JsonObject)jv;
    map.put(jo.getString("key"), jo.getString("value") );
}
System.out.println(map);

I am using a JsonReader to convert the String to a JsonArray object. Each entry of this JsonArray is a JsonObject like {key: keyX, value: valueX}. I get the values corresponding to 'key' and 'value' and add them to a HashMap using a for loop.

Nice Books
  • 1,675
  • 2
  • 17
  • 21