JAVA uses Gson to parse json data, instance, and gsonjson

Source: Internet
Author: User

JAVA uses Gson to parse json data, instance, and gsonjson

Encapsulation class Attribute:

public class Attribute {private int id;private String name;private int age;public int getId() {return id;}public void setId(int id) {this.id = id;}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;}}

Another encapsulation class GsonDataAnalysis:

public class GsonDataAnalysis {private List<Attribute> list;public List<Attribute> getList() {return list;}public void setList(List<Attribute> list) {this.list = list;}}

Main method of the test class:

/*** Gson parses json data * @ author ForeverLover * @ version 2015-04-19 */public class GsonTest {public static void main (String [] args) {String sTotalString = "{\" list \ ": [" + "{\" id \ ": \" 1 \ ", \" name \": \ "Tom \", \ "age \": \ "12 \"}, "+" {\ "id \": \ "2 \", \ "name \": \ "Marry \", \ "age \": \ "18 \"} "+"]} "; Gson gson = new Gson (); gsonDataAnalysis gda = gson. fromJson (sTotalString, GsonDataAnalysis. class); for (int I = 0; I <gda. getList (). size (); I ++) {System. out. print ("ID:" + gda. getList (). get (I ). getId () + ""); System. out. print ("Last Name:" + gda. getList (). get (I ). getName () + ""); System. out. println ("Age:" + gda. getList (). get (I ). getAge ());}}}

Note: when using the Gson class, add the Gson. jar package to the project.

Reprinted with the source: http://www.cnblogs.com/ForeverLover/p/4438694.html

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.