Detailed Gson use (a) Simple object conversion

Source: Internet
Author: User
Tags tojson

JSON is a lightweight data interchange format. Easy to read and write, but also easy to machine parse and generate ( typically used to improve network transfer rates ).

before I wrote an article, " Android parsing JSON Data "

http://blog.csdn.net/a249900679/article/details/51195505

introduced the JSON and using Jsonobject , Jsonarray parsing JSON data, the following articles will explain JSON A better way to get data: using Gson parsing.

Gson is a Google introduced to parse JSON data and converting objects to JSON the framework of the data. You can easily convert JSON data to and from objects, and you can customize the fields that you want to serialize or deserialize.

Use Gson need to import first Jar , what I'm using here is Gson-2.3.1.jar

Projects andJar:

Github :https://github.com/smileysx/GsonTest

Oschina :Https://git.oschina.net/ysx_xx/GsonText



Detailed Gson use (a) Simple object conversion

http://blog.csdn.net/a249900679/article/details/51385913

Detailed Gson use (ii) a list conversion with generics

http://blog.csdn.net/a249900679/article/details/51386028

Detailed Gson use (iii) use of annotations

http://blog.csdn.net/a249900679/article/details/51386509

Detailed Gson use (iv) Map object conversion
http://blog.csdn.net/a249900679/article/details/51386660
Detailed Gson use (v) to achieve Baidu translation function

http://blog.csdn.net/a249900679/article/details/51386727


which Gson-2.3.1.jar in the project Lib directory under

Here's a first introduction to the transformation of simple objects:

Note: The variable names for all of the following entity classes are JSON in the data Key same

1. Common JSON data Object entity class:

public class Tojsonbeanone {private int id;private string name;private int age;public tojsonbeanone (int id, string name, I NT age) {super (), this.id = Id;this.name = Name;this.age = age;} public int getId () {return ID;} Public String GetName () {return name;} public int getage () {return age;} public void setId (int id) {this.id = ID;} public void SetName (String name) {this.name = name;} public void Setage (int.) {this.age = age;}  @Overridepublic string toString () {String resultstring = ""; Resultstring + = "ID:" + ID + "\nname:" + name + "\nage:" + Age + "\ n"; return resultstring;}}

As you can see, the three data in the above object is of type string, which is the simplest.

See how to serialize the object:

public class Tojsontest extends Activity {private TextView show;private Button start;private gson Gson; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_ Main); InitData ();} private void InitData () {Gson = new Gson (); show = (TextView) Findviewbyid (r.id.showtext); start = (Button) Findviewbyid (r.i D.send); Start.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {showData ();}});} private void ShowData () {String resultstring = ""; resultstring = one () + "\ n"; Show.settext (resultstring);} Private String One () {//create object Tojsonbeanone Tojsonbeanone = new Tojsonbeanone (1, "Cubs", 21);//Convert object to JSON data return Gson.tojson (Tojsonbeanone);}}

The result is:



then see how to convert the JSON data to that object:

public class Fromjsontest extends Activity {/** * display data TextView */private TextView show;/** * button */private button start;/* * * Gson */private gson gson; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (R.layout.activity_main); InitData ();} private void InitData () {Gson = new Gson (); show = (TextView) Findviewbyid (r.id.showtext); start = (Button) Findviewbyid (r.i D.send); Start.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {showData ();}});} private void ShowData () {String showstring = ""; showstring + = one (); Show.settext (showstring);} Private String One () {//Creates an object here, in order to get the JSON data, the actual JSON data may be obtained by the network request Tojsonbeanone Tojsonbeanone = new Tojsonbeanone (1, "Cubs ", 21); String jsonstring = Gson.tojson (Tojsonbeanone);//Convert JSON data to object Tojsonbeanone Beanone = Gson.fromjson (jsonstring, Tojsonbeanone.class); String showstring = ""; showstring + = "JSON:" + jsonstring + "\ n Parse result: \ n" + beanone.tostring (); showstring + = "----------------------\ n "; return showstring;}} 

The result is:



2. object entity class with object:

public class Tojsonbeantwo {private string School;private string Classroom;private tojsonbeanone tojsonbeanone;public Tojsonbeantwo (string School, String Classroom,tojsonbeanone tojsonbeanone) {super (); this.school = School; This.classroom = Classroom;this.tojsonbeanone = Tojsonbeanone;} Public String Getschool () {return school;} Public String Getclassroom () {return classroom;} Public Tojsonbeanone Gettojsonbeanone () {return tojsonbeanone;} public void Setschool (String school) {this.school = school;} public void Setclassroom (String classroom) {this.classroom = classroom;} public void Settojsonbeanone (Tojsonbeanone tojsonbeanone) {this.tojsonbeanone = Tojsonbeanone;} @Overridepublic string toString () {String resultstring = ""; resultstring + = "School:" + School + "\nclassroom:" + Classroo m+ "\ntojsonbeanone:\nid:" + tojsonbeanone.getid () + "\nname:" + tojsonbeanone.getname () + "\nage:" + Tojsonbeanone.getage () + "\ n"; return resultstring;}}

you can see that there are not only string type data in this object , but also tojsonbeanone object data.

See how to serialize the object:

public class Tojsontest extends Activity {private TextView show;private Button start;private gson Gson; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_ Main); InitData ();} private void InitData () {Gson = new Gson (); show = (TextView) Findviewbyid (r.id.showtext); start = (Button) Findviewbyid (r.i D.send); Start.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {showData ();}});} private void ShowData () {String resultstring = ""; resultstring + = three () + "\ n"; Show.settext (resultstring);} Private String Three () {Tojsonbeantwo tojsonbeantwo = new Tojsonbeantwo ("Hua soft", "soft Five class", New Tojsonbeanone (1, "cubs", +)); Retu RN Gson.tojson (Tojsonbeantwo);}}

The result is:



data to that object:

public class Fromjsontest extends Activity {/** * display data TextView */private TextView show;/** * button */private button start;/* * * Gson */private gson gson; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (R.layout.activity_main); InitData ();} private void InitData () {Gson = new Gson (); show = (TextView) Findviewbyid (r.id.showtext); start = (Button) Findviewbyid (r.i D.send); Start.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {showData ();}});} private void ShowData () {String showstring = ""; showstring + = three (); Show.settext (showstring);} Private String Three () {Tojsonbeantwo tojsonbeantwo = new Tojsonbeantwo ("Huayi", "Soft Five class", New Tojsonbeanone (1, "Cubs", 21)); String jsonstring = Gson.tojson (tojsonbeantwo); Tojsonbeantwo beantwo = Gson.fromjson (jsonstring, Tojsonbeantwo.class); String showstring = ""; showstring + = "JSON:" + jsonstring + "\ n parsed data: \ n" + beantwo.tostring (); showstring + = "------------ ----------\ n "; retUrn showstring;}} 

The result is:



3. object with both object and list data (equivalent to the array in JSON data) entity class:

public class Tojsonbeanthree {private String number;private tojsonbeantwo tojsonbeantwo;private list<book> Books; Public Tojsonbeanthree (String number, tojsonbeantwo tojsonbeantwo,list<book> books) {super (); this.number = Number;this.tojsonbeantwo = Tojsonbeantwo;this.books = books;} Public Tojsonbeantwo Gettojsonbeantwo () {return tojsonbeantwo;} Public list<book> Getbooks () {return books;} public void Settojsonbeantwo (Tojsonbeantwo tojsonbeantwo) {this.tojsonbeantwo = Tojsonbeantwo;} public void Setbooks (List<book> books) {this.books = books;} Public String GetNumber () {return number;} public void Setnumber (String number) {this.number = number;} @Overridepublic string toString () {String resultstring = ""; resultstring + = "Number:" + number + "\ n"; Tojsonbeanone Tojsonbeanone = Tojsonbeantwo.gettojsonbeanone (); resultstring + = "Tojsonbeantwo:\nschool:" + Tojsonbeantwo.getschool () + "\nclassroom:" + tojsonbeantwo.getclassroom () + "\ n"; resultstring + = "Tojsonbeanone:\nid:" + tOjsonbeanone.getid () + "\nname:" + tojsonbeanone.getname () + "\nage:" + tojsonbeanone.getage () + "\ n"; resultstring + = " Books:\n "; for (int i = 0; i < books.size (); ++i) {resultstring + =" BookName: "+ books.get (i). Getbookname () +" \nprice: " + Books.get (i). GetPrice () + "\ n";} return resultstring;} /** * * @ClassName: Book * @Description: Inner class * @author smile * @date May 12, 2016 morning 12:23:42 * */public static class book {private string bookname;private float price;public book (String bookname, float price) {super (); this.bookname = BookName; This.price = Price;} Public String Getbookname () {return bookname;} public float GetPrice () {return price;} public void Setbookname (String bookname) {this.bookname = BookName;} public void Setprice (float price) {this.price = Price;}}}

It can be seen that there are not only string types in this object, but also the Tojsonbeantwo object type, and the list<book> type, book object I write the inner class, if there are more than one class shared is written as an external class, here to note: Write the inner class to be written as static inner class, Otherwise the parsing will go wrong.

See how to serialize the object:

public class Tojsontest extends Activity {private TextView show;private Button start;private gson Gson; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_ Main); InitData ();} private void InitData () {Gson = new Gson (); show = (TextView) Findviewbyid (r.id.showtext); start = (Button) Findviewbyid (r.i D.send); Start.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {showData ();}});} private void ShowData () {String resultstring = ""; resultstring + = five () + "\ n"; Show.settext (resultstring);} Private String Five () {tojsonbeantwo tojsonbeantwo = new Tojsonbeantwo ("Huayi", "Soft Five class", New Tojsonbeanone (1, "Cubs", 21)); list<book> books = new arraylist<book> (); for (int i = 1; i < 5; ++i) {Books.add ("the" + i + "book", 25 f * i));} Tojsonbeanthree tojsonbeanthree = new Tojsonbeanthree ("1", tojsonbeantwo, books); return Gson.tojson (Tojsonbeanthree);}}

The result is:


you can see that the list data in the object books converted to JSON data into an array

then see how to convert the JSON data to that object:

public class Fromjsontest extends Activity {/** * display data TextView */private TextView show;/** * button */private button start;/* * * Gson */private gson gson; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (R.layout.activity_main); InitData ();} private void InitData () {Gson = new Gson (); show = (TextView) Findviewbyid (r.id.showtext); start = (Button) Findviewbyid (r.i D.send); Start.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {showData ();}});} private void ShowData () {String showstring = ""; showstring + = Five (); Show.settext (showstring);} Private String Five () {tojsonbeantwo tojsonbeantwo = new Tojsonbeantwo ("Huayi", "Soft Five class", New Tojsonbeanone (1, "Cubs", 21)); list<book> books = new arraylist<book> (); for (int i = 1; i < 5; ++i) {Books.add ("the" + i + "book", 25 f * i));} Tojsonbeanthree tojsonbeanthree = new Tojsonbeanthree ("1", tojsonbeantwo, books); String jsonstring = Gson.tojson (tojsonbeanthree); Tojsonbeanthree Beanthree = Gson.fromjson (Jsonstring,tojsonbeanthree.class); String showstring = ""; showstring + = "JSON:" + jsonstring + "\ n parsed data: \ n" + beanthree.tostring (); showstring + = "----------- -----------\ n "; return showstring;}}

The result is:




Detailed Gson use (a) Simple object conversion

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.