Convert JSON String to JSON Object in Java



The JSON stands for JavaScript Object Notation and it can be used to transfer and storage of data.  
The JSONObject can parse text from a String to produce a map-like object. The object provides methods for manipulating its contents, and for producing a JSON compliant object serialization. The JSONArray can parse text from a String to produce a vector-like object. The object provides methods for manipulating its contents, and for producing a JSON compliant array serialization.

In the below two examples, We can convert a JSON string to a JSON object.

Example 1

import org.json.JSONObject;
import org.json.JSONArray;
public class StringToJSONTest {
   public static void main(String args[]) {
      String str = "[{\"No\":\"1\",\"Name\":\"Adithya\"},{\"No\":\"2\",\"Name\":\"Jai\"}, {\"No\":\"3\",\"Name\":\"Raja\"}]";
      JSONArray array = new JSONArray(str);
      for(int i=0; i < array.length(); i++) {
         JSONObject object = array.getJSONObject(i);
         System.out.println(object.getString("No"));
         System.out.println(object.getString("Name"));
      }
   }
}

Output

1
Adithya
2
Jai
3
Raja


Example 2

import org.json.*;
public class StringToJsonObjectTest {
   public static void main(String[] args) {
      String str = "{\"name\": \"Raja\", \"technology\": \"Java\"}";
      JSONObject json = new JSONObject(str);
      System.out.println(json.toString());
      String tech = json.getString("technology");
      System.out.println(tech);
   }
}

Output

{"name":"Raja","technology":"Java"}
Java
Updated on: 2020-07-03T14:06:49+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements