Advertisement
Advertisement


How to convert jsonString to JSONObject in Java


Question

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...

2018/08/31
1
440
8/31/2018 12:04:10 PM

Accepted Answer

Using org.json library:

try {
     JSONObject jsonObject = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
}catch (JSONException err){
     Log.d("Error", err.toString());
}
2019/05/30
698
5/30/2019 3:11:45 PM

To anyone still looking for an answer:

JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringToParse);
2014/09/30

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

(Serialization)

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.

(Deserialization)

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

}

Output

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

Resources:

Google Gson Project Home Page

Gson User Guide

Example

2011/03/09

There are various Java JSON serializers and deserializers linked from the JSON home page.

As of this writing, there are these 22:

...but of course the list can change.

2019/05/24

Java 7 solution

import javax.json.*;

...

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

;

2015/03/23

To convert String into JSONObject you just need to pass the String instance into Constructor of JSONObject.

Eg:

JSONObject jsonObj = new JSONObject("your string");
2016/12/20

Source: https://stackoverflow.com/questions/5245840
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]