How to convert jsonString to JSONObject in Java
To convert a JSON string to a JSONObject in Java, you can use the JSONObject constructor that takes a String as an argument, like this:
To convert a JSON string to a JSONObject in Java, you can use the JSONObject constructor that takes a String as an argument. First, ensure you have the org.json library in your project:
Maven:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20231013</version>
</dependency>Gradle:
implementation 'org.json:json:20231013'Include the necessary imports and handle JSONException as shown below:
import org.json.JSONObject;
import org.json.JSONException;
public class Main {
public static void main(String[] args) {
String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
try {
JSONObject jsonObject = new JSONObject(jsonString);
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
String city = jsonObject.getString("city");
System.out.println(name + ", " + age + ", " + city);
} catch (JSONException e) {
e.printStackTrace();
}
}
}Alternatively, you can use the Jackson library to parse JSON strings. Here's an example using ObjectMapper and JsonNode:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main {
public static void main(String[] args) throws Exception {
String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(jsonString);
String name = jsonNode.get("name").asText();
int age = jsonNode.get("age").asInt();
String city = jsonNode.get("city").asText();
System.out.println(name + ", " + age + ", " + city);
}
}