我有一个名为jsonString的字符串变量:

{"phonetype":"N95","cat":"WP"}

现在我想把它转换成JSON对象。我在谷歌上搜索了更多,但没有得到任何预期的答案!


当前回答

Codehaus Jackson -自2012年以来,我一直是这个很棒的API,用于我的RESTful webservice和JUnit测试。使用它们的API,你可以:

(1)转换JSON字符串到Java bean

public static String beanToJSONString(Object myJavaBean) throws Exception {
    ObjectMapper jacksonObjMapper = new ObjectMapper();
    return jacksonObjMapper.writeValueAsString(myJavaBean);
}

(2)将JSON字符串转换为JSON对象(JsonNode)

public static JsonNode stringToJSONObject(String jsonString) throws Exception {
    ObjectMapper jacksonObjMapper = new ObjectMapper();
    return jacksonObjMapper.readTree(jsonString);
}

//Example:
String jsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";   
JsonNode jsonNode = stringToJSONObject(jsonString);
Assert.assertEquals("Phonetype value not legit!", "N95", jsonNode.get("phonetype").getTextValue());
Assert.assertEquals("Cat value is tragic!", "WP", jsonNode.get("cat").getTextValue());

(3)转换Java bean到JSON字符串

    public static Object JSONStringToBean(Class myBeanClass, String JSONString) throws Exception {
    ObjectMapper jacksonObjMapper = new ObjectMapper();
    return jacksonObjMapper.readValue(JSONString, beanClass);
}

参考文献:

Codehaus杰克逊 JsonNode API——如何使用、导航、解析和计算来自JsonNode对象的值 教程-简单的教程,如何使用Jackson将JSON字符串转换为JsonNode

其他回答

不需要使用任何外部库。

你可以使用这个类代替:)(处理甚至列表,嵌套列表和json)

public class Utility {

    public static Map<String, Object> jsonToMap(Object json) throws JSONException {

        if(json instanceof JSONObject)
            return _jsonToMap_((JSONObject)json) ;

        else if (json instanceof String)
        {
            JSONObject jsonObject = new JSONObject((String)json) ;
            return _jsonToMap_(jsonObject) ;
        }
        return null ;
    }


   private static Map<String, Object> _jsonToMap_(JSONObject json) throws JSONException {
        Map<String, Object> retMap = new HashMap<String, Object>();

        if(json != JSONObject.NULL) {
            retMap = toMap(json);
        }
        return retMap;
    }


    private static Map<String, Object> toMap(JSONObject object) throws JSONException {
        Map<String, Object> map = new HashMap<String, Object>();

        Iterator<String> keysItr = object.keys();
        while(keysItr.hasNext()) {
            String key = keysItr.next();
            Object value = object.get(key);

            if(value instanceof JSONArray) {
                value = toList((JSONArray) value);
            }

            else if(value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            map.put(key, value);
        }
        return map;
    }


    public static List<Object> toList(JSONArray array) throws JSONException {
        List<Object> list = new ArrayList<Object>();
        for(int i = 0; i < array.length(); i++) {
            Object value = array.get(i);
            if(value instanceof JSONArray) {
                value = toList((JSONArray) value);
            }

            else if(value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            list.add(value);
        }
        return list;
    }
}

将JSON字符串转换为hashmap使用:

HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(

必须导入org.json

JSONObject jsonObj = null;
        try {
            jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
        } catch (JSONException e) {
            e.printStackTrace();
        }

使用org.json

如果你有一个包含JSON格式文本的字符串,那么你可以通过以下步骤获取JSON对象:

String jsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
JSONObject jsonObj = null;
    try {
        jsonObj = new JSONObject(jsonString);
    } catch (JSONException e) {
        e.printStackTrace();
    }

现在访问phonetype

Sysout.out.println(jsonObject.getString("phonetype"));

注意,反序列化接口的GSON将导致如下异常。

"java.lang.RuntimeException: Unable to invoke no-args constructor for interface XXX. Register an InstanceCreator with Gson for this type may fix this problem."

而反序列化;GSON不知道该接口需要调用哪个对象。

这个问题在这里得到了解决。

然而FlexJSON本身就有这个解决方案。而序列化时间,它是添加类名作为json的一部分,如下所示。

{
    "HTTPStatus": "OK",
    "class": "com.XXX.YYY.HTTPViewResponse",
    "code": null,
    "outputContext": {
        "class": "com.XXX.YYY.ZZZ.OutputSuccessContext",
        "eligible": true
    }
}

JSON会有些麻烦;但是你不需要编写GSON中需要的InstanceCreator。

你可以使用google-gson。细节:

对象的例子

class BagOfPrimitives {
  private int value1 = 1;
  private String value2 = "abc";
  private transient int value3 = 3;
  BagOfPrimitives() {
    // no-args constructor
  }
}

(序列化)

BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj); 
==> json is {"value1":1,"value2":"abc"}

注意,不能用循环引用序列化对象,因为那会导致无限递归。

(反序列化)

BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);  
==> obj2 is just like obj

Gson的另一个例子:

Gson很容易学习和实现,你需要知道的是以下两种方法:

-> toJson() -转换java对象到JSON格式

-> fromJson() -转换JSON为java对象

import com.google.gson.Gson;

public class TestObjectToJson {
  private int data1 = 100;
  private String data2 = "hello";

  public static void main(String[] args) {
      TestObjectToJson obj = new TestObjectToJson();
      Gson gson = new Gson();

      //convert java object to JSON format
      String json = gson.toJson(obj);

      System.out.println(json);
  }

}

输出

{"data1":100,"data2":"hello"}

资源:

谷歌Gson项目首页

Gson用户指南

例子