Gson is a Java class library that Google provides to map between Java objects and JSON data. You can turn a JSON string into a Java object, or vice versa. Direct reference in Android Studio
Compile ' com.google.code.gson:gson:2.2.4 '
Let's look at how to convert the object:
The entity classes are as follows:
public class Testeneity {
/**
* Image:image/mango_cover.jpg
* Content: Hot imported Malaysian Specialties Big Gold Mango Package mail 500G
* price:18.9
* preferentialprice:14.9
* You: free postage
* number:23
*/
Private String image;
Private String content;
Private String Price;
Private String Preferentialprice;
Private String for you;
private String number;
Public String GetImage () {
return image;
}
public void SetImage (String image) {
This.image = image;
}
Public String getcontent () {
return content;
}
public void SetContent (String content) {
this.content = content;
}
Public String GetPrice () {
return price;
}
public void Setprice (String price) {
This.price = Price;
}
Public String Getpreferentialprice () {
return preferentialprice;
}
public void Setpreferentialprice (String preferentialprice) {
This. Preferentialprice = Preferentialprice;
}
Public String getyou () {
return to you;
}
public void Setyou (String) {
This.you = you;
}
Public String GetNumber () {
return number;
}
public void Setnumber (String number) {
This.number = number;
}
}
How to use:
Testeneity testentity=new testeneity ();
Testentity.setimage ("image/mango_cover.jpg");
Testentity.setcontent (" hot imported Malaysian specialty large gold mango 500g");
Testentity.setprice ("18.9");
Testentity.setpreferentialprice ("14.9");
Testentity.setyou (" free ");
Testentity.setnumber ("23");
System.out.println ("----------conversion between simple objects-------------");
Simple Bean to JSON
Gson gson=new Gson ();
String S1 = Gson.tojson (testentity);
System.out.println (" simple Bean converted to json===" + S1);
JSON to Simple bean
Testeneity Tset = Gson.fromjson (S1, Testeneity.class);
System.out.println (" JSON to Simple bean===" + Tset);
list< Testeneity> Testentitylist=new arraylist<> ();
for (int i=0;i<3;i++) {
Testeneity testentity=new testeneity ();
Testentity.setimage ("image/mango_cover.jpg");
Testentity.setcontent (" hot imported Malaysian specialty large gold mango 500g");
Testentity.setprice ("18.9");
Testentity.setpreferentialprice ("14.9");
Testentity.setyou (" free ");
Testentity.setnumber ("23");
Testentitylist.add (testentity);
System.out.println ("----------Conversion-------------") between the list with generics;
Converting a list with generics to JSON
Gson gson=new Gson ();
String s2 = Gson.tojson (testentitylist);
SYSTEM.OUT.PRINTLN (" with generic list conversion to json==" + s2);
JSON to a list with generics
list< Testeneity> Retlist = Gson.fromjson (S2,
New typetoken< list< Testeneity>> () {
}.gettype ());
for (testeneity stu:retlist) {
System.out.println (Stu);
}
}