How to convert jsonString to JSONObject in Java How to convert jsonString to JSONObject in Java json json

How to convert jsonString to JSONObject in Java

Using org.json library:

try {     JSONObject jsonObject = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");}catch (JSONException err){     Log.d("Error", err.toString());}

To anyone still looking for an answer:

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

You can use google-gson. Details:

Object Examples

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

Note that you can not serialize objects with circular references since that will result in infinite recursion.


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

Another example for Gson:

Gson is easy to learn and implement, you need to know is the following two methods:

-> toJson() – convert java object to JSON format

-> fromJson() – convert JSON into java object

import;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);  }}




Google Gson Project Home Page

Gson User Guide