About Me

My photo
Ernakulam, Kerala, India
I am Sajadh, author of this blog. I run this with loads of passion.
If you are into java, you may find lot of interesting things around ...
Advance thanks for your queries to sajadhaja90@gmail.com.

Tuesday, 12 March 2013

Creating & Parsing JSON data with Java


JSON.org has provided libraries to create/parse JSON data through Java code.

LIBRARY 1  :- json-rpc library 

 Download JAR file json-rpc-1.0.jar (75 kb)

JSONObject class :- 
·         to create JSON data in Java.
·         It is an unordered collection of name/value pairs
·         Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names
·         Its internal form is an object having get() and opt() methods for accessing the values by name, and put() methods for adding or replacing values by name.
·         The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.

Example

import org.json.JSONObject;
...
...

JSONObject json = new JSONObject();
json.put("city", "Mumbai");
json.put("country", "India");

...

String output = json.toString();

...

   Thus by using toString() method you can get the output in JSON format.

JSONArray class :-

·         It is an ordered sequence of values.
·         Its external text form is a string wrapped in square brackets with commas separating the values.
·         The internal form is an object having get and opt methods for accessing the values by index, and put methods for adding or replacing values.
·         The values can be any of these types: Boolean, JSONArray, JSONObject, Number, String, or the JSONObject.NULL object


LIBRARY 2 :- json-lib library

JSON-lib is a java library for transforming beans, maps, collections, java arrays and XML to JSON and back again to beans and DynaBeans.

Download: json-lib.jar

Json-lib requires (at least) the following dependencies in your classpath:
  1. jakarta commons-lang 2.5
  2. jakarta commons-beanutils 1.8.0
  3. jakarta commons-collections 3.2.1
  4. jakarta commons-logging 1.1.1
  5. ezmorph 1.0.6

Example

package net.viralpatel.java;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

public class JsonMain {
    public static void main(String[] args) {
         
        Map<String, Long> map = new HashMap<String, Long>();
        map.put("A", 10L);
        map.put("B", 20L);
        map.put("C", 30L);
         
        JSONObject json = new JSONObject();
        json.accumulateAll(map);
         
        System.out.println(json.toString());

         List<String> list = new ArrayList<String>();
        list.add("Sunday");
        list.add("Monday");
        list.add("Tuesday");
         
        json.accumulate("weekdays", list);
        System.out.println(json.toString());
    }
}
Output:
{"A":10,"B":20,"C":30}
{"A":10,"B":20,"C":30,"weekdays":["Sunday","Monday","Tuesday"]}

LIBRARY 3:- Google Gson library

·         Gson is a Java library that can be used to convert Java Objects into their JSON representation.
·         It can also be used to convert a JSON string to an equivalent Java object.
·         Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

Gson Goals :

  • Provide simple toJson() and fromJson() methods to convert Java objects to JSON and vice-versa
  • Allow pre-existing unmodifiable objects to be converted to and from JSON
  • Extensive support of Java Generics
  • Allow custom representations for objects
  • Support arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types).

Example

import java.util.List;
import com.google.gson.Gson;

public class Test {

    public static void main(String... args) throws Exception {
        String json =
            "{"
                + "'title': 'Computing and Information systems',"
                + "'id' : 1,"
                + "'children' : 'true',"
                + "'groups' : [{"
                    + "'title' : 'Level one CIS',"
                    + "'id' : 2,"
                    + "'children' : 'true',"
                    + "'groups' : [{"
                        + "'title' : 'Intro To Computing and Internet',"
                        + "'id' : 3,"
                        + "'children': 'false',"
                        + "'groups':[]"
                    + "}]"
                + "}]"
            + "}";

        // Now do the magic.
        Data data = new Gson().fromJson(json, Data.class);

        // Show it.
        System.out.println(data);
    }

}
class Data {
    private String title;
    private Long id;
    private Boolean children;
    private List<Data> groups;

    public String getTitle() { return title; }
    public Long getId() { return id; }
    public Boolean getChildren() { return children; }
    public List<Data> getGroups() { return groups; }

    public void setTitle(String title) { this.title = title; }
    public void setId(Long id) { this.id = id; }
    public void setChildren(Boolean children) { this.children = children; }
    public void setGroups(List<Data> groups) { this.groups = groups; }

    public String toString() {
        return String.format("title:%s,id:%d,children:%s,groups:%s", title, id, children, groups);
    }

                                                      NEXT PAGE





No comments:

Post a Comment

You can enter queries here...