views:

1304

answers:

6

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 );
+1  A: 

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

Lluis Martinez
+2  A: 

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);
Taylor Leese
This one did the work. I like Gson better for bean binding but unfortunately in my environment I can't use generics on which Gson relies heavily. JSON-Simple have a little bug though which I think could be easily solved: http://code.google.com/p/json-simple/issues/detail?id=18 I'm using this anyway, thanks for the link
OscarRyz
+1  A: 

Using the google-gson library http://code.google.com/p/google-gson/ it looks like you could write something along the lines of

String json = "{'data1':100,'data2':'hello'}";
Gson gson = new Gson();
Map obj = gson.fromJson(json, Map.class);

and

Map obj = new Map();
Gson gson = new Gson();
String json = gson.toJson(obj);
-1 because the `fromJson` sample doesn't work, it throws `java.lang.IllegalArgumentException: Map objects need to be parameterized unless you use a custom serializer. Use the com.google.gson.reflect.TypeToken to extract the ParameterizedType.`
OscarRyz
+6  A: 

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

}
BalusC
Is there a way to decode ( deserialize ) to non generic map ?
OscarRyz
Either replace `Map<String, String>` by `Map<String, Object>` or `Map<Object, Object>`. Or, more OO-friendly, just use a fullworthy Javabean. Gson can handle it perfectly as well. See this answer for an example: http://stackoverflow.com/questions/1688099/converting-json-to-java/1688182#1688182
BalusC
The problem is I'm using an environment that doesn't support generics, ( erhmm. don't ask me how or why, I just, can't use them ) and what I'm trying to find is a way to convert plain lists of maps to json and have them back.
OscarRyz
I see. Does it run Java 1.5 at any way? Else Gson won't run at any way. You may consider to have a look at Jackson then: http://jackson.codehaus.org/ (tutorial here http://jackson.codehaus.org/Tutorial, `Ctrl+F` on "untyped" to achieve the same what you want). The reason I suggest Jackson is by the way because it is **fast**. Benchmarks here BTW: http://www.cowtowncoder.com/blog/archives/2009/02/entry_204.html
BalusC
+1 ...15 chars.
OscarRyz
Awesome answer. I've totally missed the TypeToken class, and could't remember what I did wrong. Thank you. :)
Lyubomyr Shaydariv
+1  A: 

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

The Elite Gentleman