参考:
https://github.com/google/gson
https://google.github.io/gson/apidocs/com/google/gson/Gson.html
编译环境配置参考:
https://search.maven.org/artifact/com.google.code.gson/gson/2.8.5/jar
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.LinkedList;
import java.util.List;
public class Main {
static public class MyType {
String name;
int id;
MyType(String name, int id) {
this.name = name;
this.id = id;
}
}
public static void SingleObjectTest() {
Gson gson = new Gson(); // Or use new GsonBuilder().create();
MyType target = new MyType("harryhare",1234);
String json = gson.toJson(target); // serializes target to Json
System.out.println(json);
MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2
System.out.println(target2.name);
System.out.println(target2.id);
}
public static void ArrayStringTest() {
Type listType = new TypeToken<List<String>>() {
}.getType();
List<String> target = new LinkedList<>();
target.add("blah");
Gson gson = new Gson();
String json = gson.toJson(target, listType);
System.out.println(json);
List<String> target2 = gson.fromJson(json, listType);
System.out.println(target2.get(0));
}
public static void ArrayObjectTest() {
Type listType = new TypeToken<List<MyType>>() {
}.getType();
List<MyType> target = new LinkedList<>();
target.add(new MyType("harryhare",1234));
Gson gson = new Gson();
String json = gson.toJson(target, listType);
System.out.println(json);
List<MyType> target2 = gson.fromJson(json, listType);
System.out.println(target2.get(0).name);
System.out.println(target2.get(0).id);
}
public static void main(String[] args) {
SingleObjectTest();
ArrayStringTest();
ArrayObjectTest();
}
}
{"name":"harryhare","id":1234}
harryhare
1234
["blah"]
blah
[{"name":"harryhare","id":1234}]
harryhare
1234