Android uses Gson to process JSON

Source: Internet
Author: User

JSON is an XML-like common data Interchange Format, which is more efficient than XML. It is more advantageous for the network to transmit data. Here, some use the Gosn class to process JSON data. Gson is faster than traditional JSON processing and gson open source. If you are interested, you can also learn about Ali development of the Fastgson, the speed is very fast.

Using GOSN to process JSON is straightforward. First we first create a JavaBean class

(1) Create User.java

 Public classUser { PublicUser (String name,intAge ) {         This. Name =name;  This. Age =Age ; }    PrivateString name; Private intAge ;  PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }}
View Code

(2) Parse the following JSON format data:

String Jsondata = "[{\" name\ ": \" john\ ", \" age\ ": 18},{\" name\ ": \" jason\ ", \" age\ ": 16}]";//Resolving TypesType ListType =NewTypetoken<linkedlist<user>>() {}.gettype ();//Create Gson instance, Gson Gson = new Gson ();Gson Gson =gsonfactory.getgsoninstance ();//parsing JSON datalinkedlist<user> users =Gson.fromjson (Jsondata, listtype);//Iterative Output for(Iterator Iterator =users.iterator (); Iterator.hasnext ();) {User User=(User) iterator.next (); System.out.println (User.getname ()); System.out.println (User.getage ()); }

(3) JavaBean using Gson to generate JSON data

 

 list<user> userlist=new  linkedlist<user>();  
User user1
=new User ("Zhang San", 20 User user2 =new User ("John", 45 // create Gson instance = Gson (); // Generate JSON formatted data String jsondata =gson.tojson (UserList) System.out.println (jsondata); // The output is: [{"Name": "Zhang San", "Age": 20},{"name": "John", "Age": "}]

Here the main use of Gson two methods:

1. Methods for parsing JSON Fromjson

2. How to generate JSON ToJson

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.