com.google.code.gson
gson
2.6.2
Gson gson = new Gson();
TargetType target = gson.fromJson(JSON_DATA_STRING, TargetType);
String targetString = gson.toJson(TargetObject);
Type listType = new TypeToken>(){}.getType();
GsonBuilder builder = new GsonBuilder();
builder.setDateFormat("yyyy年MM月dd HH:mm:ss");
Gson gson = builder.create();
String JSON_DATA_STRING = {
nick_name: "sagomilk"
}
public class Person {
@SerializedName("nick_name")
public String name;
}
gson.fromJson(JSON_DATA_STRING, Person.class);
Gson includeNullsGson = gsonBuilder.serializeNulls().create();
Gson unescapingGson = new GsonBuilder().disableHtmlEscaping().create();
transient String nickName;
或者 static ,如果需要输出
import java.lang.reflect.Modifier;
Gson gson = new GsonBuilder()
.excludeFieldsWithModifiers(Modifier.STATIC)
.create();
class VersionClass{
@Since(1.0)
String versionOneField = "1.0";
@Since(2.0)
String versionTwoField = "2.0";
}
Gson gson = new GsonBuilder().setVersion(1.0).create();
Serializer
private class DateTimeSerializer implements JsonSerializer {
public JsonElement serialize(DateTime src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.toString());
}
}
Deserializer
private class DateTimeDeserializer implements JsonDeserializer {
public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
return new DateTime(json.getAsJsonPrimitive().getAsString());
}
}
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(MyType2.class, new MyTypeAdapter());
gson.registerTypeAdapter(MyType.class, new MySerializer());
gson.registerTypeAdapter(MyType.class, new MyDeserializer());
gson.registerTypeAdapter(MyType.class, new MyInstanceCreator());
直接解析成数组
Person[] foos = gson.fromJson(JSON_DATA_STRING, Person[].class);
List fooList = Arrays.asList(foos);
解析成为List
Type listType = new TypeToken>(){}.getType();
ArrayList foos = gson.fromJson(JSON_DATA_STRING, listType);
如果没有对应的Object class,可以直接使用Map.class,但是使用的时候需要执行转换
Map m = gson.fromJson(JSON_DATA_STRING, Map.class);
new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES).create();
GsonBuilder gsonBuilder = new GsonBuilder();
Gson prettyGson = gsonBuilder.setPrettyPrinting().create();
FileWriter writer = new FileWriter("./data.json")) {
gson.toJson(new Person(), writer);
gson