且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从json到java.util.Map编码/解码的库?

更新时间:2022-10-20 11:53:26

JSON-Simple 看起来比较容易使用(下面的例子)。



地图到JSON:

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

JSON到列表/地图:

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


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

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