Gson操作
20282 ワード
/**
*
* Created by hyman on 2017/5/22.
*/
public class StudentTest {
public static void main(String[] args) {
Gson gson = new Gson();
Student student1 = new Student();
student1.setId("101");
student1.setUserName("hyman");
student1.setBirthday(new Date());
System.out.println("--------- java ");
String s1 = gson.toJson(student1);
//bean--->json
System.out.println(" Bean Gson==" + s1);
//json--->bean
Student student = gson.fromJson(s1, Student.class);
System.out.println("josn bean==" + student);
Student student2 = new Student();
student2.setId("102");
student2.setUserName("hyq");
student2.setBirthday(new Date());
Student student3 = new Student();
student3.setId("103");
student3.setUserName("LiSi");
student3.setBirthday(new Date());
List list = new ArrayList();
list.add(student1);
list.add(student2);
list.add(student3);
//list json
System.out.println("-------- list -----------");
String s2 = gson.toJson(list);
System.out.println(" list json==" + s2);
//json list
List retList =
gson.fromJson(s2,new TypeToken>(){}.getType());
for(Student stu:retList){
System.out.println(stu);
}
}
}
try(Writer writer = new OutputStreamWriter(new FileOutputStream("Output.json") , "UTF-8")){
Gson gson = new GsonBuilder().create();
gson.toJson("Hello", writer);
gson.toJson(123, writer);
}
public static void main(String[] args) throws IOException {
try(Reader reader = new InputStreamReader(JsonToJava.class.getResourceAsStream("/Server1.json"), "UTF-8")){
Gson gson = new GsonBuilder().create();
Person p = gson.fromJson(reader, Person.class);
System.out.println(p);
}
}
public static void main(String[] args) throws Exception {
Gson gson = new Gson();
List<String> list = Arrays.asList("1", "a", "3", "rt", "5");
log("---->list convert jsonStr:" + gson.toJson(list));
Map<String, Object> content = new HashMap<String, Object>();
content.put("name", "xuanyouwu");
content.put("age", "26");
log("---->map convert jsonStr:" + gson.toJson(content));
}
public class GsonTest2 {
private static void log(String msg) {
System.out.println(msg);
}
public static void main(String[] args) throws Exception {
String studentJsonStr="{\"name\":\"xuanyouwu\",\"age\":26}";
log("------>studentJsonStr:"+studentJsonStr);
JsonPrimitive jsonPrimitive=new JsonPrimitive(studentJsonStr);
log("------>jsonPrimitive:"+jsonPrimitive);
log("------>jsonPrimitive:"+jsonPrimitive.toString());
log("------>jsonPrimitive:"+jsonPrimitive.getAsString());
JsonPrimitive jsonPrimitive2=new JsonPrimitive("this is String");
log("------>jsonPrimitive2:"+jsonPrimitive2);
log("------>jsonPrimitive2:"+jsonPrimitive2.toString());
log("------>jsonPrimitive2:"+jsonPrimitive2.getAsString());
}
Gsonコメント
public class Box {
@SerializedName("w")
private int width;
@SerializedName("h")
private int height;
@SerializedName("d")
private int depth;
// Methods removed for brevity
}
public class Account {
@Expose(deserialize = false)
private String accountNumber;
@Expose
private String iban;
@Expose(serialize = false)
private String owner;
@Expose(serialize = false, deserialize = false)
private String address;
private String pin;
}
final GsonBuilder builder = new GsonBuilder();
builder.excludeFieldsWithoutExposeAnnotation();
final Gson gson = builder.create();
public class SoccerPlayer {
private String name;
@Since(1.2)
private int shirtNumber;
@Until(0.9)
private String country;
private String teamName;
// Methods removed for brevity
}
Gsonシーケンス化
public class Book {
private String[] authors;
@SerializedName("isbn-10")
private String isbn10;
@SerializedName("isbn-13")
private String isbn13;
private String title;
// , getter setter
}
public class BookSerialiser implements JsonSerializer {
@Override
public JsonElement serialize(final Book book, final Type typeOfSrc, final JsonSerializationContext context) {
final JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("title", book.getTitle());
jsonObject.addProperty("isbn-10", book.getIsbn10());
jsonObject.addProperty("isbn-13", book.getIsbn13());
final JsonArray jsonAuthorsArray = new JsonArray();
for (final String author : book.getAuthors()) {
final JsonPrimitive jsonAuthor = new JsonPrimitive(author);
jsonAuthorsArray.add(jsonAuthor);
}
jsonObject.add("authors", jsonAuthorsArray);
return jsonObject;
}
}
public interface JsonSerializer {
/**
*Gson T
*
* @param T Json , Book
* @return T JsonElement
*/
public JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext context);
}
final JsonObject jsonObject = new JsonObject();
jsonObject.addProperty...
jsonObject.add...
// Configure GSON
final GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Book.class, new BookSerialiser());
gsonBuilder.setPrettyPrinting();
final Gson gson = gsonBuilder.create();
final Book javaPuzzlers = new Book();
javaPuzzlers.setTitle("Java Puzzlers: Traps, Pitfalls, and Corner Cases");
javaPuzzlers.setIsbn10("032133678X");
javaPuzzlers.setIsbn13("978-0321336781");
javaPuzzlers.setAuthors(new String[] { "Joshua Bloch", "Neal Gafter" });
// Format to JSON
final String json = gson.toJson(javaPuzzlers);
System.out.println(json);
gsonBuilder.registerTypeAdapter(Book.class, new BookSerialiser())
メソッドに対応してJsonSerializerの構成を行う.上記の例では、gsonBuilder.setPrettyPrinting()
が呼び出される.方法はまたGsonに生成したJSONオブジェクトをフォーマットするGson逆シーケンス化
public class Book {
private String[] authors;
@SerializedName("isbn-10")
private String isbn10;
@SerializedName(value = "isbn-13", alternate = {"isbn13","isbn.13"})
private String isbn13;
private String title;
// , getter setter
}
ここでは@SerializedName注記でvalue,alternateフィールド,valueつまりデフォルトのフィールドを使用しており、シーケンス化と逆シーケンス化に有効であり、alternateは逆シーケンス化のみが効果的であることがわかります.つまり、一般サーバがJSONデータを返してくれたときに同じ画像が「image」、「img」、「icon」などを表す可能性があります.@SerializedNameのalternateフィールドを利用して、この問題を解決し、すべて私たちのエンティティクラスの図面フィールドに変換します.-2逆シーケンス化スキーム2-シーケンス化の際に使用するのはJsonSerializeであり、ここではJsonDeserializerを使用することに対応する-解析したjsonデータをBookのsetterメソッドに渡すだけでよい.
public class BookDeserializer implements JsonDeserializer<Book> {
@Override
public Book deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
throws JsonParseException {
final JsonObject jsonObject = json.getAsJsonObject();
final JsonElement jsonTitle = jsonObject.get("title");
final String title = jsonTitle.getAsString();
final String isbn10 = jsonObject.get("isbn-10").getAsString();
final String isbn13 = jsonObject.get("isbn-13").getAsString();
final JsonArray jsonAuthorsArray = jsonObject.get("authors").getAsJsonArray();
final String[] authors = new String[jsonAuthorsArray.size()];
for (int i = 0; i < authors.length; i++) {
final JsonElement jsonAuthor = jsonAuthorsArray.get(i);
authors[i] = jsonAuthor.getAsString();
}
final Book book = new Book();
book.setTitle(title);
book.setIsbn10(isbn10);
book.setIsbn13(isbn13);
book.setAuthors(authors);
return book;
}
}
final JsonObject jsonObject = json.getAsJsonObject()
を通りますJsonElementをJsonObject jsonObject.get("xxx").getAsString()
の形式で対応するStringの値jsonObject.get("xx").getAsJsonArray()
を通過する.対応するjson配列を取得し、対応するフィールド値// Configure Gson
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Book.class, new BookDeserializer());
Gson gson = gsonBuilder.create();
// The JSON data
try(Reader reader = new InputStreamReader(Main.class.getResourceAsStream("/part1/sample.json"), "UTF-8")){
// Parse JSON to Java
Book book = gson.fromJson(reader, Book.class);
System.out.println(book);
}