Skip to content

Instantly share code, notes, and snippets.

@jmcabandara
Forked from madan712/TestJSON.java
Created September 28, 2015 06:56
Show Gist options
  • Save jmcabandara/59a24ec9756f048278bd to your computer and use it in GitHub Desktop.
Save jmcabandara/59a24ec9756f048278bd to your computer and use it in GitHub Desktop.
Java program to Convert JSONObject to JSON String and vice versa
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);
//convert from JSONObject to JSON string
String jsonText = jObject.toJSONString();
System.out.println(jsonText);
JSONParser parser = new JSONParser();
//convert from JSON string to JSONObject
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"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment