Give an example of Java JSON Class library Gson basic usage _java

Source: Internet
Author: User
Tags dateformat tojson

Gson This Java class library converts Java objects to JSON or converts JSON strings into an equal Java object. Gson supports arbitrary complex Java objects including objects that have no source code.
Other JSON parsing libraries and Json-lib;jackson;com.alibaba.fastjson.
Small series or like Google's Gson.

First, the use of the scene:
conversion between Java objects and JSON strings;
For example:

Logger Logger = Logger.getlogger (commonaction.class);
Gson g = new Gson ();
Logger.info ("Return:" +g.tojson (map)); 

Second, the use of examples:
1. Basic Usage Tojson
Tojason () method converts an object to a JSON string

Gson Gson = new Gson ();
List persons = new ArrayList ();
String str = gson.tojson (persons); 

2. Basic usage: Fromjson ()
Gson provides a Fromjson () method for converting from a JSON string to a Java entity.
For example, the JSON string is:

[{' name ': ' NAME0 ', ' age ': 0}]

The

 
 

provides two parameters, namely, the JSON string and the type of object that needs to be converted.
3. Avoid Unicode escape
For example: {"S": "\u003c"} I just want to simply print this {"S": "<"} solution: I just need disable HTML escaping. Gson Gson = new

Gsonbuilder (). disablehtmlescaping (). Create (); 

4. Exclude certain fields
if a Class A contains a field field1, and its parent class also contains a field field1, then the A object Tojson occurs declares multiple JSON fields named. Solution 1: Remove the field filed1 in Class A. Solution 2: Use the @expose annotation of JSON to add annotations @expose to the fields that need to be printed in Class A messagetext. The field1 that are not annotated in the parent class are excluded.

Gson g = new Gsonbuilder (). Excludefieldswithoutexposeannotation (). Create (); 

5. Change the name of the property


third, the use of examples:

Import Java.lang.reflect.Type;
Import Java.sql.Timestamp;
Import Java.text.DateFormat;
Import Java.text.SimpleDateFormat;
Import java.util.ArrayList;
Import Java.util.Date;

Import java.util.List;
Import Com.google.gson.Gson;
Import Com.google.gson.GsonBuilder;
Import Com.google.gson.JsonDeserializationContext;
Import Com.google.gson.JsonDeserializer;
Import com.google.gson.JsonElement;
Import com.google.gson.JsonParseException;
Import com.google.gson.JsonPrimitive;
Import Com.google.gson.JsonSerializationContext;
Import Com.google.gson.JsonSerializer;


Import Com.google.gson.reflect.TypeToken;
 public class Gsondemo {public static void main (string[] args) {//Gson Gson = new Gson (); Sets the format for converting properties of a type Gson Gson = new Gsonbuilder (). Registertypeadapter (Timestamp.class, New Timestamptypeadapter ()).
 Setdateformat ("Yyyy-mm-dd HH:mm:ss"). Create ();
 list<person> persons = new arraylist<person> ();
    for (int i = 0; i < i++) {person p = new person (); P.setname ("NAMe "+ i);
    P.setage (i * 5);
    P.setinserttime (New Timestamp (System.currenttimemillis ()));
 Persons.add (P);
 String str = gson.tojson (persons);
 
 System.out.println (str);
 list<person> PS = Gson.fromjson (str, new typetoken<list<person>> () {}.gettype ());
    for (int i = 0; i < ps.size (); i++) {Person p = ps.get (i);
 System.out.println (P.tostring ());
 } System.out.println (New Timestamp (System.currenttimemillis ()));
 Class Person {private String name;
 private int age;

 Private Timestamp Inserttime;
 Public String GetName () {return name;
 public void SetName (String name) {this.name = name;
 public int getage () {return age;
 public void Setage (int age) {this.age = age;
 Public Timestamp Getinserttime () {return inserttime;
 public void Setinserttime (Timestamp inserttime) {this.inserttime = Inserttime;
 @Override public String toString () {return name + ' \ t ' + age + ' \ t ' + inserttime;
}//implementation serialization, deserialization interfaceClass Timestamptypeadapter implements Jsonserializer<timestamp>, jsondeserializer<timestamp> {public Jsonelement Serialize (Timestamp src, Type arg1, Jsonserializationcontext arg2) {dateformat format = new Simpledatefor
    Mat ("Yyyy-mm-dd HH:mm:ss:SS");
    String dateformatasstring = Format.format (New Date (Src.gettime ()));
  return new jsonprimitive (dateformatasstring); Timestamp Deserialize (jsonelement json, Type Typeoft, Jsondeserializationcontext context) throws Jsonparseexce ption {if (!) (
    JSON instanceof Jsonprimitive)) {throw new Jsonparseexception ("The date should be a string value");
      try {dateformat format = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss:SS");
      Date date = (date) format.parse (json.getasstring ());
    return new Timestamp (Date.gettime ());
    catch (Exception e) {throw new Jsonparseexception (e);
 }
  }

}

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.