Convert Java Object to / from JSON using JSON.simple

We can use json-simple library parse a JSON string to Java object and vice versa.

The jar can be downloaded from : https://code.google.com/archive/p/json-simple/
 
Here are some examples:

 

Example : Convert Java Object to JSON String

package com.topjavatutorial.json;

import org.json.simple.JSONObject;

public class JsonParsingExample {

  public static void main(String[] args) {
    JSONObject jsonObj  = new JSONObject();
    jsonObj.put("empName", "John Doe");
    jsonObj.put("employeeId", "101");
    jsonObj.put("age","25");
    
    System.out.println(jsonObj.toJSONString());
  }

}


 
Output:

{“name”:”John Doe”,”employeeId”:”101″,”age”:”25″}

 

Example : Convert JSON String to Java Object

package com.topjavatutorial.json;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JsonParsingExample {

  public static void main(String[] args) {
    String jsonString = "{\"name\":\"John Doe\",\"employeeId\":\"101\",\"age\":\"25\"}";
    JSONParser parser = new JSONParser();
    JSONObject obj;
    try {
      obj = (JSONObject) parser.parse(jsonString);

      System.out.println(obj.get("name"));
      System.out.println(obj.get("employeeId"));
      System.out.println(obj.get("age"));

    } catch (ParseException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

  }

}


 
Output:

John Doe
101
25
 

We can also use the following for JSON processing:

Converting JSON to / from Java Object using Jackson

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags