DatamineR
DatamineR

Reputation: 9618

Convert a JSON object to a Map object

I have a JSON object which look as the following:

[{"var1":"value1","var2":"value2"},{"var2":"value22","var3":[["0","1","2"],["3","4","5"],["6","7","8"]]}]

(Note: var2 appears twice in the example and the complex form of the value of var3.)

The desired output should be a map object like:

key   value
var1  value1
var2  value2,value22
var3  [["0","1","2"],["3","4","5"],["6","7","8"]]

What I would like is to convert this to a map object with the first elements (var1, var2, var3) as keys and the corresponding values as the values in the map. In case with the identical keys (e.g.: var2) the two values which belong to this key shoul be concatenated, but separated, e.g., by a comma.

Can someone help me with this?

Upvotes: 0

Views: 3596

Answers (2)

Sharon Ben Asher
Sharon Ben Asher

Reputation: 14328

You don't need an adapter to parse a json. you just need to tell ObjectMapper exactly what type to parse into. you also need a bit of post processing since you want some special processing regarding duplicate keys

you get Jackson from GIT: https://github.com/FasterXML/jackson

here is a complete solution for you:

import java.util.*;

import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.type.TypeFactory;

public class Test
{
    public static void main(String[] args)
    {
        String input = "[{\"var1\":\"value1\",\"var2\":\"value2\"},{\"var2\":\"value22\",\"var3\":[[\"0\",\"1\",\"2\"],[\"3\",\"4\",\"5\"],[\"6\",\"7\",\"8\"]]}]" ;
        Map<String, String> result = new HashMap<>();  // final result, with duplicate keys handles and everything

        try {
            // ObjectMapper is Jackson json parser 
            ObjectMapper om = new ObjectMapper();
            // we need to tell ObjectMapper what type to parse into 
            // in this case: list of maps where key is string and value is some cimplex Object
            TypeFactory tf = om.getTypeFactory();
            JavaType mapType = tf.constructMapType(HashMap.class, String.class, Object.class);
            JavaType listType = tf.constructCollectionType(List.class, mapType);
            @SuppressWarnings("unchecked")
            // finally we parse the input into the data struct 
            List<Map<String, Object>> list = (List<Map<String, Object>>)om.readValue(input, listType);

            // post procesing: populate result, taking care of duplicates 
            for (Map<String, Object> listItem : list) {
                for (Map.Entry<String, Object> mapItem : listItem.entrySet()) {
                    String key = mapItem.getKey();
                    String value = mapItem.getValue().toString();
                    if (result.containsKey(key)) value = result.get(key) + "," + value;
                    result.put(key, value);
                }
            }

            // result sohuld hold expected outut now 
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

output:

{var3=[[0, 1, 2], [3, 4, 5], [6, 7, 8]], var2=value2,value22, var1=value1}

Upvotes: 1

Noushad
Noushad

Reputation: 512

You can use Jackson to convert to and from JSON to Map. Use the following code and instantiate the JSonAdapter class, use the method marshal(String) to convert the json string to map and unmarshall(Map) for vice versa.

import java.io.IOException;
import java.util.Map;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonAdapter {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    public String unmarshal(final Map<?, ?> jsonList) throws Exception {
        return MAPPER.writeValueAsString(jsonList);
    }

    public Map<?, ?> marshal(final String jsonString) throws Exception {

        try {
            return MAPPER.readValue(jsonString, new TypeReference<Map<?, ?>>() {
            });
        } catch (final IOException e) {
            e.printStackTrace();
        }

        return null;
    }

}

Upvotes: 1

Related Questions