Learning The "J"

Home » JAVA Learning » JAVA EE » Parsing JASON » Parsing JASON Using Google GSON API

Parsing JASON Using Google GSON API

package logtest;

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

public class JasonParsing {

    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.
        //System.out.println(json); 
        Data data = new Gson().fromJson(json, Data.class);

        // Show it.
        System.out.print(data.title + "  ");        
        System.out.println(data.id);        
        
        System.out.print(data.groups.get(0).title + "  ");        
        System.out.println(data.groups.get(0).id);        
        
        System.out.print(data.groups.get(0).groups.get(0).title +"  ");        
        System.out.print(data.groups.get(0).groups.get(0).id +"  ");
        
    }

    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);
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Start here

%d bloggers like this: