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 );
We can easily convert JSON data into a map because the JSON format is essentially a key-value pair grouping and the map also stores data in key-value pairs. Let's understand how we can use both JACKSON and Gson libraries to convert JSON data into a Map.
We need to use the JSON-lib library for serializing and de-serializing a Map in JSON format. Initially, we can create a POJO class and pass this instance as an argument to the put() method of Map class and finally add this map instance to the accumulateAll() method of JSONObject.
You can map the data types of your business model into JSON by using the examples. Data in JSON is either an object or an array. A JSON object is an unordered collection of names and values. A JSON array is an ordered sequence of values.
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}
}
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With