How to create JSON Object using String?
To create a JSON object from a string in Java, you can use the org.json
library. Here's an example of how you can do this:
String jsonString = "{\"key1\": \"value1\", \"key2\": \"value2\"}";
JSONObject jsonObject = new JSONObject(jsonString);
This code will create a JSONObject
with the following contents:
{
"key1": "value1",
"key2": "value2"
}
You can then access the values in the JSON object using the get
method:
String value1 = jsonObject.getString("key1");
String value2 = jsonObject.getString("key2");
You can also use the org.json
library to create a JSON object from scratch, by adding key-value pairs to the object using the put
method:
JSONObject jsonObject = new JSONObject();
jsonObject.put("key1", "value1");
jsonObject.put("key2", "value2");
I hope this helps! Let me know if you have any questions.