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

时间:2010-03-22 23:28:23

标签: java json map converter

有谁知道一个可以轻松地将java Maps编码为json对象的java库,反之亦然?

更新

由于原因无法解释(我有时讨厌)我不能在我的环境中使用泛型。

我想做的是做这样的事情:

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

  */ 

能够再次将其作为地图列表

 List aList = ( List ) fromJson( jsonStirng );

6 个答案:

答案 0 :(得分:33)

您可以使用Google Gson。它对Generic types有很好的支持。

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

}

答案 1 :(得分:14)

JSON-Simple看起来相对容易使用(以下示例)。

映射到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);

答案 2 :(得分:4)

您可以从Json.org查看该站点,以获取Java中的优秀JSON库列表。

JSon.org自己的implementation JSONObject可以做到这一点。 来自他们的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);

你可以做到

JSONObject json = new JSONObject(map);

将JSON String转换回object ....

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

您可以访问以下值:

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

构造函数JavaDoC

  

从源构造JSONObject   JSON文本字符串。这是最多的   常用的JSONObject构造函数。

     

参数:source一个字符串开头   使用{(左括号)并以}结尾   (右支撑)。

答案 3 :(得分:3)

我想真正的问题是哪个JSON库(来自org.json的页面)不允许这样做。据我所知,每个库都会以某种形式允许它。 所以到目前为止提到的每个图书馆都有效。

要添加一些信息,Jackson可以很好地处理各种数据,包括基本地图和列表:

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

将处理这种特殊情况。虽然可以使用泛型类型信息,但在使用“自然”绑定到JDK容器类型时它是可选的。

答案 4 :(得分:1)

我们在项目中使用http://json-lib.sourceforge.net/,效果很好。

答案 5 :(得分:0)

使用google gson。

var getRowData =
[{
    "dayOfWeek": "Sun",
    "date": "11-Mar-2012",
    "los": "1",
    "specialEvent": "",
    "lrv": "0"
},
{
    "dayOfWeek": "Mon",
    "date": "",
    "los": "2",
    "specialEvent": "",
    "lrv": "0.16"
}];

    JsonElement root = new JsonParser().parse(request.getParameter("getRowData"));
     JsonArray  jsonArray = root.getAsJsonArray();
     JsonObject  jsonObject1 = jsonArray.get(0).getAsJsonObject();
     String dayOfWeek = jsonObject1.get("dayOfWeek").toString();

//使用杰克逊时

    JsonFactory f = new JsonFactory();
              ObjectMapper mapper = new ObjectMapper();
          JsonParser jp = f.createJsonParser(getRowData);
          // advance stream to START_ARRAY first:
          jp.nextToken();
          // and then each time, advance to opening START_OBJECT
         while (jp.nextToken() == JsonToken.START_OBJECT) {
            Map<String,Object> userData = mapper.readValue(jp, Map.class);
            userData.get("dayOfWeek");
            // process
           // after binding, stream points to closing END_OBJECT
        }
相关问题