最近学习到了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
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 = int.class);
Integer one = gson.fromJson("1", Integer.class);
Long.class);
Boolean false = Boolean.class);
String str = String anotherStr =
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();
String json = gson.toJson(obj);
==> json is {"value1":1,"value2":"abc"} //注意 这里没有出现 value3 = 3
java 关键字transient
如果用transient声明一个实例变量,当对象存储时,它的值不需要维持
Gson 也就不会序列化他
(Deserialization)
BagOfPrimitives obj2 = );
Finer Points with Objects //小小细节 1.
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
//数组例子
int[] ints = {1, 2, 3, 4,
5};
String[] strings = {"abc",
"def", "ghi"};
(Serialization)
gson.toJson(ints);
==> prints
[1,2,3,4,5]
(Deserialization)
int[] ints2 = );
==> 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;
}
}