I have String variable called jsonString
:
{\"phonetype\":\"N95\",\"cat\":\"WP\"}
Now I want to convert it into JSON Object. I
Java 7 solution
import javax.json.*;
...
String TEXT;
JsonObject body = Json.createReader(new StringReader(TEXT)).readObject()
;
you must import org.json
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
} catch (JSONException e) {
e.printStackTrace();
}
Using org.json
If you have a String containing JSON format text, then you can get JSON Object by following steps:
String jsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
Now to access the phonetype
Sysout.out.println(jsonObject.getString("phonetype"));
To anyone still looking for an answer:
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringToParse);
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.
Better Go with more simpler way by using org.json
lib. Just do a very simple approach as below:
JSONObject obj = new JSONObject();
obj.put("phonetype", "N95");
obj.put("cat", "WP");
Now obj
is your converted JSONObject
form of your respective String. This is in case if you have name-value pairs.
For a string you can directly pass to the constructor of JSONObject
. If it'll be a valid json String
, then okay otherwise it'll throw an exception.