Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can we convert a JSON string to a 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"}
JavaAdvertisements