简体   繁体   中英

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 (eg: var2 ) the two values which belong to this key shoul be concatenated, but separated, eg, by a comma.

Can someone help me with this?

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;
    }

}

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}

There is no predefined API to perform your operation, you have to write you own parser to convert JSONObject to Map .

See some hint below:

public static Map<String, Object> toMap(JSONObject object) throws JSONException{
    Map<String, List<String>> map = new HashMap<String, List<String>>();
    Iterator<String> keysIterator = object.keys();
    while(keysIterator .hasNext()) {
        String key = keysIterator.next();
        Object value = object.get(key);

        if(map.contains(key)){
         ... //do your task
        }

       ... //get value of the key 

      map.put(key, yourValue)
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM