Library to encode/decode from json to java.util.Map?

39,025

Solution 1

JSON-Simple looks relatively easy to use (examples below).

Map to JSON:

  Map map = new HashMap();
  map.put("name", "foo");
  map.put("nickname", "bar");
  String jsonText = JSONValue.toJSONString(map);

JSON to List/Map:

  String s = yourJsonString;
  List list = (JSONArray) JSONValue.parse(s);       
  Map map = (JSONObject) list.get(0);

Solution 2

You can use Google Gson for that. It has excellent support for Generic types.

Here's an SSCCE:

package com.stackoverflow.q2496494;

import java.util.LinkedHashMap;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class Test {

   public static void main(String... args) {
        Map<String, String> map = new LinkedHashMap<String, String>();
        map.put("key1", "value1");
        map.put("key2", "value2");
        map.put("key3", "value3");
        Gson gson = new Gson();

        // Serialize.
        String json = gson.toJson(map);
        System.out.println(json); // {"key1":"value1","key2":"value2","key3":"value3"}

        // Deserialize.
        Map<String, String> map2 = gson.fromJson(json, new TypeToken<Map<String, String>>() {}.getType());
        System.out.println(map2); // {key1=value1, key2=value2, key3=value3}
    }

}

Solution 3

You can view the site from Json.org for the list of good JSON libraries in Java.

JSon.org's own implementation JSONObject can do just that. From their JavaDoC

 /**
     * Construct a JSONObject from a Map.
     * 
     * @param map A map object that can be used to initialize the contents of
     *  the JSONObject.
     */
    public JSONObject(Map map);

you can do

JSONObject json = new JSONObject(map);

To convert JSON String back to object....

String jsonString = "{\"name\" : \"some name\", \"age\" : 10}";
JSONObject json = new JSONObject(jsonString);

and you can access values like:

int age = json.getInt("age");

Constructor JavaDoC

Construct a JSONObject from a source JSON text string. This is the most commonly used JSONObject constructor.

Parameters: source A string beginning with { (left brace) and ending with } (right brace).

Solution 4

I guess the real question would be which JSON library (from org.json's page) would NOT allow doing this. As far as I know every single library there would allow this in some form. So every library mentioned so far works.

And to add some information, Jackson works very well with all kinds of data including basic Maps and Lists:

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValue(list);
List listOfMaps = mapper.readValue(json, List.class);

which would handle this particular case. While generic type information can be used, it is optional when using "natural" binding to JDK container types.

Solution 5

We use http://json-lib.sourceforge.net/ in our project, it works just fine.

Share:
39,025
OscarRyz
Author by

OscarRyz

Software Developer who happens to like writing code. Here are some interesting answers you might like to upvote :") Why java people frequently consume exception silently ? Coding in Other (Spoken) Languages How to create an string from the contents of a file History of Objective-C square brackets (as I remember it) ( visible only to &gt;10k users )

Updated on April 23, 2020

Comments

  • OscarRyz
    OscarRyz about 4 years

    Does anyone knows a java library that could easily encode java Maps into json objects and the other way around?

    UPDATE

    For reasons couldn't explain ( and I hate sometimes ) I can't use generics on my environment.

    What' I'm trying to do is to have something like this:

    Map a = new HashMap();
    a.put( "name", "Oscar" );
    
    Map b = new HashMap();
    b.put( "name", "MyBoss"); 
    a.put( "boss",  b ) ;
    
    
    List list = new ArrayList();
    list.add( a );
    list.add( b );
    
    
     String json = toJson( list );
     // and create the json:
     /*
        [
           {
             "name":"Oscar",
             "boss":{
                  "name":"MyBoss"
             }
            },
            {
                "name":"MyBoss"
            }
         ]
    
      */ 
    

    And be able to have it again as a list of maps

     List aList = ( List ) fromJson( jsonStirng );