LayneYao的博客

天道酬勤,运筹帷幄

Android框架---Google官方Gson解析(下)

Gson还有一种更高级的手法进行序列化和反序列化,那就是TypeAdapter ,就是就是对象json之间的互相转换 接替了T 泛型类的序列化和反序列化的逻辑,大家如果有兴趣可以去看一下源码,2.1版本之前后的用法是不一样的,2.1版本之前可以自定义adapter,在2.1版本之后更推荐直接插入泛型就使用。在这里演示泛型的

代码演示:

public class TypeAdapterTest {
	public static class Person {
		private int per_id;
		private String name;
		private String sex;
		private boolean state;

		public Person(int per_id, String name, String sex, boolean state) {
			this.per_id = per_id;
			this.name = name;
			this.sex = sex;
			this.state = state;
		}

		@Override
		public String toString() {
			return "Person-->[per_id=" + per_id + ", name=" + name + ", sex="
					+ sex + ", state=" + state + "]";
		}
	}

	public static void main(String[] args) throws Exception {
		Gson gson = new Gson();
		TypeAdapter<Person> personTypeAdapter = gson.getAdapter(Person.class);
		Person person = new Person(1, "layne", "man", true);
		String json_str = personTypeAdapter.toJson(person);
		System.out.println("序列化结果:" + json_str);

		Person person1 = personTypeAdapter.fromJson(json_str);
		System.out.println("反序列化结果:" + person1);

	}

}

运行结果:





接下来就是容错机制

为什么要容错了?
在javaBean中编号per_id声明的事int类,如果服务端返回的是""空字符串,那么客户端该怎么办?崩溃吗?
这时候就需要容错机制啦,容错的实现方式:
1.创建Gson的方式
2.使用JsonReader  
3.自定义TypeAdapter
4.使用注解JsonAdapter,其实也是自定义Adapter

1和2可以归为一类 由框架实现,基本json大格式规范,键值对不标准,多引号的问题等等,而不报错停止解析,但是功能相对较弱,能解决bug 

方式1:Gson的创建方式

gson = new GsonBuilder()  
                  .setLenient()// json宽松  
                  .create();  

方式2:使用JsonReader

JsonReader jsonReader = gson.newJsonReader(value.charStream());
jsonReader.setLenient(true);


 3和4也可以归为一类,都属于自定义adapter,但是方式3与gson绑定,方式4使用注解和字段绑定

代码示例:(这种方式比较倾向于整体)

public class FaultToleranceTest {

	public static class Person {
		private int per_id;
		private String name;
		private String sex;
		private boolean state;

		public Person() {

		}

		public Person(int per_id, String name, String sex, boolean state) {
			this.per_id = per_id;
			this.name = name;
			this.sex = sex;
			this.state = state;
		}

		@Override
		public String toString() {
			return "Person-->[per_id=" + per_id + ", name=" + name + ", sex="
					+ sex + ", state=" + state + "]";
		}
	}

	public static class PersonTypeAdapter extends TypeAdapter<Person> {

		@Override
		public Person read(JsonReader in) throws IOException {
			Person person = new Person();
			in.beginObject();
			while (in.hasNext()) {
				switch (in.nextName()) {
				case "per_id":
					try {
						String str = in.nextString();
						person.per_id = Integer.valueOf(str);
					} catch (Exception e) {
					}
					break;
				case "name":
					person.name = in.nextString();
					break;
				case "sex":
					person.sex = in.nextString();
					break;
				case "state":
					person.state = in.nextBoolean();
					break;
				}
			}
			in.endObject();
			return person;
		}

		@Override
		public void write(JsonWriter out, Person person) throws IOException {
			out.beginObject();
			out.name("per_id").value(person.per_id);
			out.name("name").value(person.name);
			out.name("sex").value(person.sex);
			out.name("state").value(person.state);
			out.endObject();

		}

	}

	public static void main(String[] args) {
		Gson gson = new Gson();

		String json_str = "{\"per_id\":\"\",\"name\":\"layne\",\"sex\":\"man\",\"state\":true}";
		System.out.println("服务端发送:" + json_str);
		try {
			Person person = gson.fromJson(json_str, Person.class);
			System.out.println("默认Gson解析:" + person);
		} catch (JsonParseException e) {// java.lang.NumberFormatException:
										// empty String
			System.out.println("默认Gson解析异常:" + e);
		}

		Gson gson2 = new GsonBuilder().registerTypeAdapter(Person.class,
				new PersonTypeAdapter()).create();
		try {
			Person person2 = gson2.fromJson(json_str, Person.class);
			System.out.println("自定义PersonTypeAdapter解析:" + person2);
		} catch (JsonParseException e) {// java.lang.NumberFormatException:
										// empty String
			System.out.println("自定义PersonTypeAdapter解析异常:" + e);
		}

		try {
			PersonTypeAdapter personTypeAdapter = new PersonTypeAdapter();
			Person person3 = personTypeAdapter.fromJson(json_str);
			System.out.println("自定义PersonTypeAdapter解析2:" + person3);
		} catch (Exception e) {
			System.out.println("自定义PersonTypeAdapter解析异常2:" + e);
		}
	}

}

运行结果:



上面的方式是倾向于整体的,下面是注解的方式,比较倾向于字段

代码演示:

public class FaultToleranceTest1 {

	public static class Person {
		@JsonAdapter(IntegerTypeAdapter.class)
		private int per_id;
		private String name;
		private String sex;
		private boolean state;

		public Person() {

		}

		public Person(int per_id, String name, String sex, boolean state) {
			this.per_id = per_id;
			this.name = name;
			this.sex = sex;
			this.state = state;
		}

		@Override
		public String toString() {
			return "Person-->[per_id=" + per_id + ", name=" + name + ", sex="
					+ sex + ", state=" + state + "]";
		}
	}

	public static class Person1 {
		private int per_id;
		private String name;
		private String sex;
		private boolean state;

		public Person1() {

		}

		public Person1(int per_id, String name, String sex, boolean state) {
			this.per_id = per_id;
			this.name = name;
			this.sex = sex;
			this.state = state;
		}

		@Override
		public String toString() {
			return "Person1-->[per_id=" + per_id + ", name=" + name + ", sex="
					+ sex + ", state=" + state + "]";
		}
	}

	public static class IntegerTypeAdapter extends TypeAdapter<Integer> {

		@Override
		public void write(JsonWriter out, Integer value) throws IOException {
			out.value(value);
		}

		@Override
		public Integer read(JsonReader in) throws IOException {
			int i = 0;
			try {
				String str = in.nextString();
				i = Integer.valueOf(str);
			} catch (Exception e) {
			}
			return i;
		}
	}

	public static void main(String[] args) {
		Gson gson = new Gson();

		String json_str = "{\"per_id\":\"\",\"name\":\"layne\",\"sex\":\"man\",\"state\":true}";
		System.out.println("服务器发送:" + json_str);
		try {
			Person1 person1 = gson.fromJson(json_str, Person1.class);
			System.out.println("gson解析:" + person1);
		} catch (Exception e) {
			System.out.println("gson解析异常:" + e);
		}

		try {
			Person person = gson.fromJson(json_str, Person.class);
			System.out.println("JsonAdapter注解解析:" + person);
		} catch (JsonParseException e) {// java.lang.NumberFormatException:
										// empty String
			System.out.println("JsonAdapter注解异常:" + e);
		}
	}

}

运行结果:



上面的两种方式保险是很保险的,但是代码量大,需要维护的地方也多,这里介绍另外一种方式:JsonSerializer与JsonDeserializer 之关系单方面的处理,可以全局注册某个类型的处理

代码演示:

public class FaultToleranceTest2 {

	public static class Person {
		private int per_id;
		private String name;
		private String sex;
		private boolean state;

		public Person() {

		}

		public Person(int per_id, String name, String sex, boolean state) {
			this.per_id = per_id;
			this.name = name;
			this.sex = sex;
			this.state = state;
		}

		@Override
		public String toString() {
			return "Person-->[per_id=" + per_id + ", name=" + name + ", sex="
					+ sex + ", state=" + state + "]";
		}
	}

	public static void main(String[] args) {
		JsonDeserializer<Integer> jsonDeserializer = new JsonDeserializer<Integer>() {

			@Override
			public Integer deserialize(JsonElement json, Type arg1,
					JsonDeserializationContext arg2) throws JsonParseException {
				try {
					return json.getAsInt();
				} catch (NumberFormatException e) {
					return 0;
				}
			}

		};

		String json_str = "{\"per_id\":\"\",\"name\":\"layne\",\"sex\":\"man\",\"state\":true}";
		System.out.println("服务器发送:" + json_str);

		Gson gson = new Gson();
		try {
			Person person1 = gson.fromJson(json_str, Person.class);
			System.out.println("默认gson解析:" + person1);
		} catch (Exception e) {
			System.out.println("默认gson解析异常:" + e);
		}
		
		//方式1.创建Gson的方式
		Gson gson1 = new GsonBuilder().registerTypeAdapter(int.class,
				jsonDeserializer).create();
		try {
			Person person = gson1.fromJson(json_str, Person.class);
			System.out.println("JsonDeserializer<Integer>解析:" + person);
		} catch (Exception e) {
			System.out.println("JsonDeserializer<Integer>解析异常:" + e);
		}

	}

}

运行结果:



阅读更多

扫码向博主提问

去开通我的Chat快问

jsagacity

一个技术人
  • 擅长领域:
  • Android开发
  • 偏物联网方向
版权声明:著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明作者和出处。 https://blog.csdn.net/Jsagacity/article/details/78256892
文章标签: gson json
个人分类: Android
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭