How to convert jsonString to JSONObject in Java

2018-12-31 06:24发布

I have String variable called jsonString:

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

Now I want to convert it into JSON Object. I searched more on Google but didn't get any expected answers...

16条回答
后来的你喜欢了谁
2楼-- · 2018-12-31 06:56

To convert a string to json and the sting is like json. {"phonetype":"N95","cat":"WP"}

String Data=response.getEntity().getText().toString(); // reading the string value 
JSONObject json = (JSONObject) new JSONParser().parse(Data);
String x=(String) json.get("phonetype");
System.out.println("Check Data"+x);
String y=(String) json.get("cat");
System.out.println("Check Data"+y);
查看更多
皆成旧梦
3楼-- · 2018-12-31 06:59

Java 7 solution

import javax.json.*;

...

String TEXT;
JsonObject body = Json.createReader(new StringReader(TEXT)).readObject()

;

查看更多
笑指拈花
4楼-- · 2018-12-31 07:00

you must import org.json

JSONObject jsonObj = null;
        try {
            jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
        } catch (JSONException e) {
            e.printStackTrace();
        }
查看更多
栀子花@的思念
5楼-- · 2018-12-31 07:02

If you are using http://json-lib.sourceforge.net (net.sf.json.JSONObject)

it is pretty easy:

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

or

JSONObject json = JSONSerializer.toJSON(myJsonString);

get the values then with json.getString(param), json.getInt(param) and so on.

查看更多
萌妹纸的霸气范
6楼-- · 2018-12-31 07:03

Use JsonNode of fasterxml for the Generic Json Parsing. It internally creates a Map of key value for all the inputs.

Example:

private void test(@RequestBody JsonNode node)

input String :

{"a":"b","c":"d"}
查看更多
不流泪的眼
7楼-- · 2018-12-31 07:04

To anyone still looking for an answer:

JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringToParse);
查看更多
登录 后发表回答