Gson gson = new Gson();
//输出"1",单个字符也可以序列化
System.out.println(gson.toJson("1"));
//输出 "fw123"
System.out.println(gson.toJson("fw123"));
//打印结果:[1,2,3] ---这种形式是数组吗?
int[] value = {1,2,3};
System.out.println(gson.toJson(value));
//上面的序列化结果都是转化成字符串类型的
// 下面是反序列化的过程
//这是一个泛型入参的函数,打印的结果: i 的值为: 1
int i = gson.fromJson("1",int.class);
System.out.println("i 的值为: " + i);
//打印出来的值为: gsonBean的值为: {"mInt":1,"mStr":"22"}--- 这个是序列化格式
String gsonBean = gson.toJson(new GsonBean(1,"22"));
System.out.println("gsonBean的值为: " + gsonBean);
SerializedName注解的使用:
public class JsonAdepterTest {
static class SerializedNameTestClass {
@SerializedName("name") //给a设置Key值为:name
String a;
@SerializedName(value = "name1", alternate = {"name2", "name3"})
String b;
String c;
public SerializedNameTestClass(String a, String b, String c) {
this.a = a;
this.b = b;
this.c = c;
}
public static void test() {
SerializedNameTestClass target =
new SerializedNameTestClass("v1", "v2", "v3");
Gson gson = new Gson();
String json = gson.toJson(target);
System.out.println(json);
}
}
public static void main(String[] args) {
SerializedNameTestClass.test();
}
}
执行结果为:{"name":"v1","name1":"v2","c":"v3"}
JsonAdapter注解的使用:
@JsonAdapter(UserJsonAdapter.class)
static
class User {
public final String firstName, lastName;
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public String toString() {
return "User{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
'}';
}
}
class UserJsonAdapter extends TypeAdapter<User> {
@Override
public void write(JsonWriter out, User user) throws IOException {
out.beginObject();
out.name("firstKey:");
out.value(user.firstName);
out.endObject();
out.beginObject();
out.name("secondKey");
out.value(user.lastName);
out.endObject();
}
@Override
public User read(JsonReader in) throws IOException {
in.beginObject();
in.nextName();
String nameParts1 = in.nextString();
in.endObject();
in.beginObject();
in.nextName();
String nameParts2 = in.nextString();
in.endObject();
return new User(nameParts1, nameParts2);
}
}
public static void main(String[] args) {
User user = new User("gg","Zero");
Gson gson = new GsonBuilder()
.setVersion(1.2).create();
String gsonStr = gson.toJson(user);
System.out.println("gsonStr=" + gsonStr);
user = gson.fromJson(gsonStr,User.class);
System.out.println("user: " + user);
}
输出结果:
gsonStr={"firstKey:":"gg"}{"secondKey":"Zero"}
user: User{firstName='gg', lastName='Zero'}
public class GsonError1 {
private String name;
private List<AuthorsBean> authors;
@Override
public String toString() {
return "GsonError1{" +
"name='" + name + '\'' +
", authors=" + authors +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<AuthorsBean> getAuthors() {
return authors;
}
public void setAuthors(List<AuthorsBean> authors) {
this.authors = authors;
}
public static class AuthorsBean {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "AuthorsBean{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
'}';
}
}
public static void test1() {
//TODO:
String json = "{\n" +
" \"name\": \"java\",\n" +
" \"authors\": [\n" +
" {\n" +
" \"id\": \"1'\",\n" +
" \"name\": \"Joshua Bloch'\"\n" +
" },\n" +
" {\n" +
" \"id\": \"2'\",\n" +
" \"name\": \"Tom\"\n" +
" }\n" +
" ]\n" +
"}";
Gson gson = new Gson();
GsonError1 gsonError1 = gson.fromJson(json, GsonError1.class);
System.out.println(gsonError1);
}
public static void main(String[] args) {
test1();
}
输出结果:
GsonError1{name='java', authors=[AuthorsBean{id='1'', name='Joshua Bloch''}, AuthorsBean{id='2'', name='Tom'}]}
String json = "{\n" +
" \"name\": \"java\",\n" +
" \"authors\": \"\"\n" +
"}";
Gson gson = new Gson();
GsonError1 gsonError1 = gson.fromJson(json, GsonError1.class);
System.out.println(gsonError1);
如果上面的Json序列化形式不对,
就会上报错误:
Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 3 column 17 path $.authors
为了解决由于Json中某些字段缺省的情况,方案一:
package com.android.serializable;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;
public class GsonError1 {
private String name;
private List<AuthorsBean> authors;
@Override
public String toString() {
return "GsonError1{" +
"name='" + name + '\'' +
", authors=" + authors +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<AuthorsBean> getAuthors() {
return authors;
}
public void setAuthors(List<AuthorsBean> authors) {
this.authors = authors;
}
public static class AuthorsBean {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "AuthorsBean{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
'}';
}
}
static class GsonError1Deserializer implements JsonDeserializer<GsonError1> {
@Override
public GsonError1 deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
final JsonObject jsonObject = json.getAsJsonObject();
final JsonElement jsonTitle = jsonObject.get("name");
final String name = jsonTitle.getAsString();
JsonElement jsonAuthors = jsonObject.get("authors");
GsonError1 gsonError1 = new GsonError1();
if (jsonAuthors.isJsonArray()) {//如果数组类型,此种情况是我们需要的
//关于context在文章最后有简单说明
GsonError1.AuthorsBean[] authors = context.deserialize(jsonAuthors, GsonError1.AuthorsBean[].class);
gsonError1.setAuthors(Arrays.asList(authors));
} else {//此种情况为无效情况
gsonError1.setAuthors(null);
}
gsonError1.setName(name);
return gsonError1;
}
}
static class AuthorDeserializer implements JsonDeserializer {
@Override
public Object deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
final JsonObject jsonObject = json.getAsJsonObject();
final GsonError1.AuthorsBean author = new GsonError1.AuthorsBean();
author.setId(jsonObject.get("id").getAsString());
author.setName(jsonObject.get("name").getAsString());
return author;
}
}
public static void test3() {
//TODO:
String json = "{\n" +
" \"name\": \"java\",\n" +
" \"authors\": \"\"\n" +
"}";
GsonBuilder gsonBuilder = new GsonBuilder();
//注册TypeAdapter
gsonBuilder.registerTypeAdapter(GsonError1.class, new GsonError1Deserializer());
gsonBuilder.registerTypeAdapter(GsonError1.AuthorsBean.class, new AuthorDeserializer());
Gson gson = gsonBuilder.create();
GsonError1 gsonError1 = gson.fromJson(json, GsonError1.class);
System.out.println(gsonError1);
}
public static void main(String[] args) {
test3();
}
}
解决方法二: 参照上面自定义TypeAdapter
Gson的源码解析
JsonToken是枚举类型.---定义Json数据的类型
/**
* A structure, name or value type in a JSON-encoded string.
*/
public enum JsonToken {
/**
* The opening of a JSON array. Written using {@link JsonWriter#beginObject}
* and read using {@link JsonReader#beginObject}.
*/
BEGIN_ARRAY,
/**
* The closing of a JSON array. Written using {@link JsonWriter#endArray}
* and read using {@link JsonReader#endArray}.
*/
END_ARRAY,
/**
* The opening of a JSON object. Written using {@link JsonWriter#beginObject}
* and read using {@link JsonReader#beginObject}.
*/
BEGIN_OBJECT,
/**
* The closing of a JSON object. Written using {@link JsonWriter#endObject}
* and read using {@link JsonReader#endObject}.
*/
END_OBJECT,
/**
* A JSON property name. Within objects, tokens alternate between names and
* their values. Written using {@link JsonWriter#name} and read using {@link
* JsonReader#nextName}
*/
NAME,
/**
* A JSON string.
*/
STRING,
/**
* A JSON number represented in this API by a Java {@code double}, {@code
* long}, or {@code int}.
*/
NUMBER,
/**
* A JSON {@code true} or {@code false}.
*/
BOOLEAN,
/**
* A JSON {@code null}.
*/
NULL,
/**
* The end of the JSON stream. This sentinel value is returned by {@link
* JsonReader#peek()} to signal that the JSON-encoded value has no more
* tokens.
*/
END_DOCUMENT
}
?JsonElement
该类是一个抽象类,代表着
json
串的某一个元素。这个元素可以是一个
Json(JsonObject)
、可以是一个 数组(JsonArray)
、可以是一个
Java
的基本类型
(JsonPrimitive)
、当然也可以为
null(JsonNull);JsonObject,JsonArray,JsonPrimitive
,
JsonNull
都是
JsonElement
这个抽象类的子类。 JsonElement提供了一系列的方法来判断当前的
JsonElement。
?