JSON知识总结- Gson(二)

1.Nested Classes (including Inner Classes)

Gson可以序列化和反序列化静态内部类

Gson can serialize static nested classes quite easily. 

Gson can also deserialize static nested classes. However, Gson can not automatically deserialize the pure inner classes 
since their no-args constructor also need a reference to the containing Object which is not available at the time of deserialization.
You can address this problem by either making the inner class static or by providing a custom InstanceCreator for it. 

public class A {
  public String a;

  class B {

    public String b;

    public B() {
      // No args constructor for B
    }
  }
}

NOTE: The above class B can not (by default) be serialized with Gson.

我试了一下,有一些不太一样,可能是没有完全理解英文的意思,或理解错了,欢迎指正;

默认的话,内部类没有默认进行序列化,即使是静态内部类也没有序列化;

内部类也可以反序列化

package org.ygy.demo;

public class A {
	public String name_a = "default a";
	
	class B {
		public String name_b = "default b";
		
		public String toString() {
			return "name_b:" + name_b;
		}
	}
	
	class C {
		public String name_c = "default c";
	}
	
	static class D {
		public String name_d = "default d";
		
		public String toString() {
			return "name_d:" + name_d;
		}
	}
}
结果:

       @Test
	public void testNested() {
		A a = new A();
	
		String json_a = gson.toJson(a);
		System.out.println("json_a" + json_a);
		
		A.B b = a.new B();
		b.name_b = "okokok";
		String json_b = gson.toJson(b);
		System.out.println("json_b" + json_b);
		
		A.B b2 = a.new B();
		b2 = gson.fromJson(json_b , A.B.class);
		System.out.println(b2);
		
		A.D d = new A.D();
		d.name_d = "hello";
		String json_d = gson.toJson(d);
		System.out.println("json_d" + json_d);
		
		A.D d2 = gson.fromJson(json_d , A.D.class);
		System.out.println(d2);
	}


InstanceCreator

public class InstanceCreatorForB implements InstanceCreator<A.B> {
  private final A a;
  public InstanceCreatorForB(A a)  {
    this.a = a;
  }
  public A.B createInstance(Type type) {
    return a.new B();
  }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值