java create jsonObject from string code example
Example 1: new jsonobject java
String message;
JSONObject json = new JSONObject();
json.put("name", "student");
JSONArray array = new JSONArray();
JSONObject item = new JSONObject();
item.put("information", "test");
item.put("id", 3);
item.put("name", "course1");
array.add(item);
json.put("course", array);
message = json.toString();
Example 2: how to convert jsonobject to json string in java
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class TestJSON {
public static void main(String[] args) {
JSONObject jObject = new JSONObject();
jObject.put("EmployeeId", new Integer(121));
jObject.put("Name", "Ramesh");
jObject.put("Salary", new Double(15000.00));
jObject.put("isPermanent", new Boolean(true));
jObject.put("Nickname", null);
String jsonText = jObject.toJSONString();
System.out.println(jsonText);
JSONParser parser = new JSONParser();
JSONObject newJObject = null;
try {
newJObject = (JSONObject) parser.parse(jsonText);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(newJObject.get("EmployeeId"));
System.out.println(newJObject.get("Name"));
System.out.println(newJObject.get("Salary"));
System.out.println(newJObject.get("isPermanent"));
System.out.println(newJObject.get("Nickname"));
}
}