Gson 学习笔记(2012-03-31 15:33:38)转载▼

出处:点击打开链接

最近学习到了Json解析 尝试过 最早 org.json

感觉 Gson 解析 json 还是很不错的 特此写了笔记已供学习!

官网是最好的学习通道
https://www.zxproxy.com/browse.php?u=PoVWZG8IRnWFg4MYzPJJAtBHtKbXBm3UMAF9kXdqMJS7W9Gap+o0TUstD6+1&b=6&f=norefer

UserGuide 解释了Gson 解析 大部分应用

Gson 用来 JavaBean --> json 格式 || json 格式 -- > JavaBean

前者称 Gson 的 序列化 后者 Gson 的反序列化


Primitives Examples //基本例子

ps Serialization :JavaBean --> json 格式
Deserialization: json 格式 -- > JavaBean




(Serialization)
Gson gson = new Gson();
gson.toJson(1); ==> prints 1
gson.toJson("abcd"); ==> prints "abcd"
gson.toJson(new Long(10)); ==> prints 10
int[] values = { 1 };
gson.toJson(values); ==> prints [1]

(Deserialization)
int one = gson.fromJson("1", int.class);
Integer one = gson.fromJson("1", Integer.class);
Long one = gson.fromJson("1", Long.class);
Boolean false = gson.fromJson("false", Boolean.class);
String str = gson.fromJson(""abc"", String.class);
String anotherStr = gson.fromJson("["abc"]", String.class);



Object Examples //自定义类
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}

(Serialization)
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
==> json is {"value1":1,"value2":"abc"} //注意 这里没有出现 value3 = 3
java 关键字transient
如果用transient声明一个实例变量,当对象存储时,它的值不需要维持
Gson 也就不会序列化他


(Deserialization)
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);


Finer Points with Objects //小小细节
1. 序列化时,一个空的字段将跳过
而反序列化,在设置对象中的相应字段中的条目丢失了JSON结果为null

如果一个字段是人工合成的,它会被忽略,不包括在JSON序列化或反序列化
相应的内部类,匿名类和局部类外类的领域被忽略,并且不包括在序列化或反序列化



Nested Classes (including Inner Classes) //嵌套类(包含内部类)
ublic class A {
public String a;

class B {

public String b;

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

//这是一个成员内部类 Gson 序列化A时 不会序列化 B
A a =new A();
a.a="aaaaaa";

A.B b =new a.new B();
b.b="bbbbbb";
Gson g =new Gson();
String atext = g.toJson(a);
System.out.println(atext);

json-->"a":"aaaaaa"


Array Examples //数组例子

Gson gson = new Gson();
int[] ints = {1, 2, 3, 4, 5};
String[] strings = {"abc", "def", "ghi"};

(Serialization)
gson.toJson(ints); ==> prints [1,2,3,4,5]

gson.toJson(strings); ==> prints ["abc", "def", "ghi"]

(Deserialization)
int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class);
==> ints2 will be same as ints

支持多维数组,任意复杂的元素类型


Collections Examples //集合<泛形>实例

Gson gson = new Gson();
Collection<Integer> ints = Lists.immutableList(1,2,3,4,5);

(Serialization)
String json = gson.toJson(ints); ==> json is [1,2,3,4,5]

(Deserialization)

//使用反序列化 如果要保持泛形
Type collectionType = new TypeToken<Collection<Integer>>(){}.getType();
Collection<Integer> ints2 = gson.fromJson(json, collectionType);
ints2 is same as ints

Fairly hideous: note how we define the type of collection
Unfortunately, no way to get around this in Java




Serializing and Deserializing Generic Types 泛型类型
Type fooType = new TypeToken<Foo<Bar>>() {}.getType();
gson.toJson(foo, fooType);

gson.fromJson(json, fooType)
Serializing and Deserializing Collection with Objects of Arbitrary Types 任意对像类型的集合
['hello',5,{name:'GREETINGS',source:'guest'}]

The equivalent Collection containing this is:
Collection collection = new ArrayList();
collection.add("hello");
collection.add(5);
collection.add(new Event("GREETINGS", "guest"));
Where the Event class is defined as:
class Event {
private String name;
private String source;
private Event(String name, String source) {
this.name = name;
this.source = source;
}
}


{name:'GREETINGS',source:'guest'} 不会被解析称Event 类


Excluding Fields From Serialization and Deserialization 过滤字段


Gson's @Expose 使用Annotaion 注解方式
@Expose
private String name;

private int age;
Gson g =new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String pStr = g.toJson(p); p 为person 的实例

只会输出name 不会输出名字

{"name":"hsahga"}

反序列化同理

User Defined Exclusion Strategies 用户自定义排出策略 解决硬编码



public class MyExclusionStrategy implements ExclusionStrategy {

private Class<?>[] clazzs; // 要过滤得类数组

private String[] fileds; //要过滤的属性数组



public MyExclusionStrategy(Class<?>[] clazzs,String[] fileds) {

this.clazzs = clazzs;
this.fileds= fileds;


}


public MyExclusionStrategy(Class<?>[] clazzs)
{

this.clazzs = clazzs ;
}


public MyExclusionStrategy(String[] fileds)
{

this.fileds = fileds ;
}




@Override
public boolean shouldSkipClass(Class<?> clazz02) {

if (this.clazzs == null) {
return false;
}

for (int i = 0; i < this.clazzs.length; i++) {

if (clazz02.getName().equals(clazzs[i].getName())) {
return true;
}
}

return false;
}



@Override
public boolean shouldSkipField(FieldAttributes f) {

if(f == null)
{
return false ;
}




for(String field : this.fileds)
{
String[] str = field.split("_");

if(f.getDeclaringClass().toString().equals(str[1]))
{

if(str[0].equals(f.getName()))
{
return true ;
}

}

}
return false;


//要使用注解排除属性 请解封下面这段话 并且屏蔽掉上面的
//return f.getAnnotation(NoSeriaizle.class) != null; 通过注解 (@NoSeriaizle)
}

}

或者通过注解 (@NoSeriaizle)

package Inner;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface NoSeriaizle {

}
在要使用的属性上:

@NoSeriaizle
private String name; 排除 name

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值