Gson learning of JSON and Java objects turning into each other

Source: Internet
Author: User
Tags tojson

Json with the Java the transfer of objects to each other Gson Learning


Please respect other people's labor results, reproduced please specify the source: Gson learning of JSON and Java objects turning into each other


I have described the conversion between Xml,object,json using XStream in the article "Xml,object,json conversion Analysis XStream use ", although XStream has built-in support for JSON, but the effect is not particularly good, after all, the XStream focus is not json. Another tool is described below.

        Gson google   gson google The company released an open source java library, mainly used for serialization java json serialization json java


1. How do I use Gson?

First from Http://code.google.com/p/google-gson/downloads/list上下载Gson的jar包,然后将其导入到项目中。然后,就可以在你的项目中使用Gson了。


2. 主要方法

The application of Gson is mainly for the two conversion methods of ToJson and Fromjson , and the class of the object must be created before using this object transformation and its members can successfully convert the JSON string to the corresponding object.


3. Application Examples of Gson
/** * Implement objects using Gson, JSON transfer * @author JPH * date:2014.09.29 */public class Gsonutil {public static Gson Gson;    /**json turn javabean**/public static final int json_javabean=0x10001;    /**json turn list<t>**/public static final int json_list=0x10002;       /**json turn map<t>**/public static final int json_map=0x10004; /** * Convert an object to a JSON-formatted string * @param object to be converted to JSON * @return String:json-formatted string */public static string                   Convertobject2json (Object object) {gson=new Gson ();    return Gson.tojson (object); /** * Convert JSON to Java Object * @param inputstream to convert to Java object InputStream * @param javaBean list Gets the Javabe contained in the map An * @param convertflag conversion type identification * @return Object:java Object */public static object Convertjson2object (Inputstre           Am Inputstream,class<?>javabean, int convertflag) {gson=new Gson ();        Object object=null;//String json=inputstream2string (InputStream); BuffereDreader Reader=intputstream2bufferedreader (InputStream);           Type Type=gettype (Javabean,convertflag);                 Object=gson.fromjson (Reader,type);    return object; }/** * Gets the type of object to convert to * @param javaBean * @param convertflag * @return * */private static type Gett        Ype (class<?> javabean,int convertflag) {Type type=null; Switch (convertflag) {case json_list:if (javabean.equals (News.class)) {//json to LIST generic Ty            Pe=new typetoken<list<news>> () {}.gettype ();        } break; Case Json_map:if (Javabean.equals (News.class)) {//json-to-MAP generics type=new Typetoken<map<strin            G,news>> () {}.gettype ();                } break;            Case Json_javabean://json turn JAVABEAN Type=javabean;                Break      } return type; }/** * Package InputStream into BufferedReader * @param inputstreAM * @return */private static BufferedReader Intputstream2bufferedreader (InputStream inputstream) {       return new BufferedReader (new InputStreamReader (InputStream)); }}


Code Analysis:

When JSON is converted to an object, the above code takes the input stream from the server side, encapsulates the input stream into a BufferedReader object, and then transforms the JSON into a Java object through the Fromjson () method.

The first parameter of the Gson Fromjson () method supports parameters of type string, Jsonelement, and reader, and can be selected as needed. The second parameter of the Fromjson () method supports parameters of type and class<?> types, and can use the class<?> parameter when the JSON is converted to JavaBean. That is to use the corresponding JavaBean JAVABEAN.CALSS as the second parameter. When you need to turn JSON out into a list generic, the map generics need to use TypeToken to convert the second parameter to type (TypeToken is a data type converter provided by Gson, which supports a variety of data collection type conversions. )。

Gson learning of JSON and Java objects turning into each other

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.