Java Json serialization and deserialization __java

Source: Internet
Author: User
Tags serialization stub tojson java se

JSON (JavaScript Object notation) is a lightweight data interchange format. Easy for people to read and write. It is also easy to machine parse and generate. It is based on JavaScript programming Language, Standard ECMA-262 a subset of 3rd Edition-december 1999. JSON uses a completely language-independent text format that makes JSON an ideal data exchange language.


Here are two Java Open source libraries that are commonly used in development to process JSON: Gson and Fastjson

1,Gson

Gson is a Java library this can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to a equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects ' you did not have of.

Gson Official website: http://code.google.com/p/google-gson/

Gson User Guide:https://sites.google.com/site/gson/gson-user-guide



2,Fastjson

The

Fastjson is a JSON processing toolkit developed by Alibaba, including serialization and deserialization, with the following characteristics:
The fastest, testing shows that Fastjson has a very fast performance beyond any other Java JSON parser. Including claiming to be the fastest Jackson. Powerful, fully supported Java Bean, collection, Map, date, Enum, support paradigm, support introspection. No dependencies, able to run directly in Java SE 5.0 version of support for Android. Open Source (Apache 2.0) Fastjson official website: Http://code.alibabatech.com/wiki/display/FastJSON/Overview

below through a simple demo, compare the two The use of serialization and deserialization
JavaBean entity person

Package com.example.testjson.entity;
Import Java.util.Date;
Import java.util.List;

Import Java.util.Map;
    public class Person {private String name;
    Private FullName FullName;
    private int age;
    Private Date birthday;
    Private list<string> Hobbies;
    Private map<string, string> clothes;
    
    Private list<person> friends;
	Public String GetName () {return name;
	public void SetName (String name) {this.name = name;
	Public FullName Getfullname () {return FullName;
	public void Setfullname (FullName FullName) {this.fullname = FullName;
	public int getage () {return age;
	public void Setage (int age) {this.age = age;
	Public Date Getbirthday () {return birthday;
	The public void Setbirthday (Date birthday) {this.birthday = birthday;
	Public list<string> gethobbies () {return hobbies;
	public void Sethobbies (list<string> hobbies) {this.hobbies = hobbies; } public map<string, STring> getclothes () {return clothes;
	public void Setclothes (map<string, string> clothes) {this.clothes = clothes;
	Public list<person> Getfriends () {return friends;
	public void Setfriends (list<person> friends) {this.friends = friends; @Override public String toString () {string str= ' person [name=] + name +, fullname= ' + fullName + ', AG  E= "+ Age +", birthday= "+ Birthday +", hobbies= "+ Hobbies +", clothes= "+ clothes +
        "]\n";
            if (friends!=null) {str+= "friends:\n";
            for (person F:friends) {str+= "\ t" +F;
    } return str;
    } class FullName {private String firstName;
    Private String MiddleName;
    
    Private String LastName;
		Public FullName () {} public FullName (string firstName, String middlename, String lastName) {super ();
		This.firstname = FirstName; This.middlename = MiddleName;
	This.lastname = LastName;
	Public String Getfirstname () {return firstName;
	} public void Setfirstname (String firstName) {this.firstname = FirstName;
	Public String Getmiddlename () {return middlename;
	} public void Setmiddlename (String middlename) {this.middlename = MiddleName;
	Public String Getlastname () {return lastName;
	} public void Setlastname (String lastName) {this.lastname = LastName; @Override public String toString () {return "[firstname=" + FirstName + ", middlename=" +
    MiddleName + ", lastname=" + LastName + "]";
 }
    
}


The Bean Factory responsible for creating the person
Package com.example.testjson.entity;
Import java.util.ArrayList;
Import Java.util.HashMap;
Import java.util.List;

Import Java.util.Map; public class Personfactory {private static person Createabsperson (String name,list<person> friends) {Pe
        Rson Newperson = new Person ();
        Newperson.setname (name);
        Newperson.setfullname (New FullName (name+ "_first", name+ "_middle", name+ "_last"));
        Newperson.setage (24);
        List<string> hobbies=new arraylist<string> ();
        Hobbies.add ("basketball");
        Hobbies.add ("swimming");
        Hobbies.add ("coding");
        Newperson.sethobbies (hobbies);
        Map<string,string> clothes=new hashmap<string, string> ();
        Clothes.put ("coat", "Nike");
        Clothes.put ("trousers", "Adidas");
        Clothes.put ("Shoes", "Anta");
        Newperson.setclothes (clothes);
        Newperson.setfriends (Friends);
    return Newperson; public static person Create (String name) {LisT<person> friends=new arraylist<person> ();
        Friends.add (Createabsperson ("xiaoming", null));
        Friends.add (Createabsperson ("Tony", null));

        Friends.add (Createabsperson ("Chen Xiao", null));
    Return Createabsperson (name,friends);
 }
}


Gson Tool Class Gsonutil
Package Com.example.testjson.gson;

Import Com.google.gson.Gson;
Import Com.google.gson.GsonBuilder;
Import com.google.gson.JsonElement;
Import Com.google.gson.JsonParser;

public class Gsonutil {
private static Gson Gson = new Gsonbuilder (). Create ();
    
    public static String Bean2json (Object obj) {return
        Gson.tojson (obj);
    }
    
    public static <T> T Json2bean (String jsonstr,class<t> objclass) {return
        Gson.fromjson jsonstr, objclass);
    }
    
    public static string Jsonformatter (String uglyjsonstr) {
        Gson Gson = new Gsonbuilder (). setprettyprinting (). Create ( );
        Jsonparser JP = new Jsonparser ();
        Jsonelement JE = jp.parse (uglyjsonstr);
        String prettyjsonstring = Gson.tojson (JE);
        Return prettyjsonstring
    }
}



Fastjson Tool Class Fastjsonutil
Package Com.example.testjson.fastjson;

Import Com.alibaba.fastjson.JSON;

public class Fastjsonutil {public
	
	static String Bean2json (Object obj) {return
        json.tojsonstring (obj);
    }
    
    public static <T> T Json2bean (String jsonstr,class<t> objclass) {return
        json.parseobject jsonstr, objclass);
    }



Last two test classes
Gsontest
Package Com.example.testjson;

Import Com.example.testjson.entity.Person;
Import com.example.testjson.entity.PersonFactory;
Import Com.example.testjson.gson.GsonUtil;

public class Gsontest {

	/**
	 * @param args */public
	static void Main (string[] args) {
		//TODO Auto-gen erated method Stub person
		p = personfactory.create ("Kobe");
		String json = Gsonutil.bean2json (p);
		String prettyjsonstring = Gsonutil.jsonformatter (JSON);
		
		System.out.println ("Fastjson serializing=" +json);
		System.out.println ("Fastjson serializing prettyprinting=" +prettyjsonstring);
		
		Person Newperson = Gsonutil.json2bean (JSON, person.class);
		
		System.out.println ("Fastjson deserializing=" +newperson);
	}




Fastjsontest

Package Com.example.testjson;

Import Com.example.testjson.entity.Person;
Import com.example.testjson.entity.PersonFactory;
Import Com.example.testjson.fastjson.FastJsonUtil;

public class Fastjsontest {

	/**
	 * @param args */public
	static void Main (string[] args) {
		//TODO Auto -generated method Stub person

		p = personfactory.create ("Kobe");
		String json = Fastjsonutil.bean2json (p);
		
		System.out.println ("Fastjson serializing=" +json);
		
		Person Newperson = Fastjsonutil.json2bean (JSON, person.class);
		
		System.out.println ("Fastjson deserializing=" +newperson);
	}






Sample Demo Download: http://download.csdn.net/detail/fx_sky/6771327






Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.