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

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

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


当前回答

对于仍在寻找答案的人:

JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringToParse);

其他回答

注意,反序列化接口的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。

必须导入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"));

如果您正在使用http://json-lib.sourceforge.net (net.sf.json.JSONObject)

这很简单:

String myJsonString;
JSONObject json = JSONObject.fromObject(myJsonString);

or

JSONObject json = JSONSerializer.toJSON(myJsonString);

获取值,然后用 json.getString(param), json.getInt(param)等等。

最好使用更简单的方式使用org。json自由。只需要做一个非常简单的方法:

JSONObject obj = new JSONObject();
obj.put("phonetype", "N95");
obj.put("cat", "WP");

现在obj是你各自String的JSONObject转换形式。这是在有名称-值对的情况下。

对于字符串,可以直接传递给JSONObject的构造函数。如果它是一个有效的json String,那么好,否则它会抛出异常。