A data exchange Json Gson

Gson is provided by Google for mapping between Java objects and JSON data Java class libraries. A JSON string can be transformed into a Java object, or vice versa.

First, the basic usage of Gson

Parsing basic data types (String to parse other types)

Gson gson = new Gson();
int i = gson.fromJson("100", int.class);              //100
double d = gson.fromJson("\"99.99\"", double.class);  //99.99
boolean b = gson.fromJson("true", boolean.class);     // true
String str = gson.fromJson("String", String.class);   // String

Generating a basic data types

Gson gson = new Gson();
String jsonNumber = gson.toJson(100);       // 100
String jsonBoolean = gson.toJson(false);    // false
String jsonString = gson.toJson("String"); //"String"

POJO class generating JSON

Gson gson = new Gson();
User user = new User("毛驴哥",24);
String jsonObject = gson.toJson(user);     // {"name":"毛驴哥","age":24}

POJO class parse JSON

Gson gson = new Gson();
String jsonString = "{\"name\":\"毛驴哥\",\"age\":24}";
User user = gson.fromJson(jsonString, User.class);

Second, the property renamed using @SerializedName annotations

The email_address can correspond json property names emailAddress

@SerializedName("email_address")
public String emailAddress;

SerializedName annotation provides two attributes, one of which is used above, there is not a property Alternate outer, receiving an array of String.

@SerializedName(value = "emailAddress", alternate = {"email", "email_address"})
public String emailAddress;

Three properties (email_address, email, emailAddress) occurs when any one of a correct result can be obtained.

Three, Gson use generics

For Java List And List Maybe has a bytecode file that is only a List.class, this is a problem when using Java generics should be noted that generics erased.
In order to solve the above problems, Gson provides TypeToken us to implement support for generics

Gson gson = new Gson();
String jsonArray = "[\"Android\",\"Java\",\"PHP\"]";
String[] strings = gson.fromJson(jsonArray, String[].class);    //直接改为 List<String>.class 是行不通
List<String> stringList = gson.fromJson(jsonArray, new TypeToken<List<String>>() {}.getType());

Note: TypeToken constructor is protected modified, it will be written on top of new TypeToken <List > () {} .GetType () instead of new TypeToken <List >().getType()

Guess you like

Origin www.cnblogs.com/loveer/p/11306338.html