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:
String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
JSONObject jsonObject = new JSONObject(jsonString);
You can then access the values in the JSONObject
using the get
method, like this:
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
String city = jsonObject.getString("city");
Alternatively, you can use a org.json
library to parse the JSON string. Here's an example using the org.json
library:
String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
JSONObject jsonObject = new JSONObject(jsonString);
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
String city = jsonObject.getString("city");