Thursday, 21 April 2016

parse JSON in Java

How to parse json in java .? Add org.json lib into your project 


public class PraseJSON {
    public static void main(String[] args) throws JSONException {
       String json = "{\n"
                + "   \"Name\": {\n"
                + "         \"Place\": \"Bangalore\",\n"
                + "         \"Age\": \"23\"\n"
                + "    }}";
              
               // + "}";

        PraseJSON classObject = new PraseJSON();
        JSONObject obj = new JSONObject(json);
        String name = obj.getJSONObject("Name").getString("Place");
        System.out.println("Name::"+name);


}}

How to Create JSON in Java ?

we can easily create JSON in java Using org.json.simple library .so build this jar into your application .

  • Create JSONObject  :

public class JSON{
 public static void main(String[] args) {

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("Name", "Anand");
        jsonObject.put("Age", new Integer(23));
        jsonObject.put("Married",new Boolean(false));


     System.out.println(jsonObject); 
/*

{"Married":false,"Age":23,"Name":"Anand"}

*/

}

  • Create JSONArray : 
 
public class JSON{
 public static void main(String[] args) {

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("Name", "Anand");
        jsonObject.put("Age", new Integer(23));
        jsonObject.put("Married",new Boolean(false));

     JSONArray jsonarray = new JSONArray();
        jsonarray.add(jsonObject);//


     System.out.println(jsonarray); 
/*
 [{"Married":false,"Age":23,"Name":"Anand"}]
*/

}


 

Map class field to map

 import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; public class AutogeneratedClassMapper {     public static M...