1import org.json.simple.JSONObject;
2import org.json.simple.parser.JSONParser;
3import org.json.simple.parser.ParseException;
4
5public class TestJSON {
6
7 public static void main(String[] args) {
8
9 JSONObject jObject = new JSONObject();
10
11 jObject.put("EmployeeId", new Integer(121));
12 jObject.put("Name", "Ramesh");
13 jObject.put("Salary", new Double(15000.00));
14 jObject.put("isPermanent", new Boolean(true));
15 jObject.put("Nickname", null);
16
17 //convert from JSONObject to JSON string
18 String jsonText = jObject.toJSONString();
19
20 System.out.println(jsonText);
21
22 JSONParser parser = new JSONParser();
23
24 //convert from JSON string to JSONObject
25 JSONObject newJObject = null;
26 try {
27 newJObject = (JSONObject) parser.parse(jsonText);
28 } catch (ParseException e) {
29 e.printStackTrace();
30 }
31
32 System.out.println(newJObject.get("EmployeeId"));
33 System.out.println(newJObject.get("Name"));
34 System.out.println(newJObject.get("Salary"));
35 System.out.println(newJObject.get("isPermanent"));
36 System.out.println(newJObject.get("Nickname"));
37 }
38}
1try {
2 JSONObject jsonObject = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
3}catch (JSONException err){
4 Log.d("Error", err.toString());
5}
6
1Jackson Data-bind depdendency that take care of
2Converting between
3JSON to Java Object
4and
5Java Object to JSON
6
7<dependency>
8 <groupId>com.fasterxml.jackson.core</groupId>
9 <artifactId>jackson-databind</artifactId>
10 <version>2.12.0</version>
11</dependency>
1I add GSON dependency in my POM --> It’s a json parser. That is
2used to convert from java object to json and from json to java
3object
4SERIALIZATION: CONVERT JAVA OBJECT -> JSON
5DE-SERIALIZATION: CONVERT JSON -> JAVA OBJECT