How can I convert String to JSON object in Java

745    Asked by SakamotoYamamoto in Java , Asked on Jul 26, 2021

 I am working on a String. I want to convert it into JSONobject. How can I do this?

Answered by Max Vance

: You can use Google gson for converting string to json java


for more details

The object in 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 of 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"}


Your Answer

Interviews

Parent Categories