Gson操作

20282 ワード

  • bean、list、およびgson変換
  • /**
     *  
     * 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);
            }
    
        }
    
    }
  • ioストリームとGson変換
  • 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);
            }
        }
  • List Map回転Json文字列
  •  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コメント

  • 1.1@SerializedName注釈
  • この注記は、このフィールドがJSONに対応するフィールド名
  • を指定することができる.
    public class Box {
    
      @SerializedName("w")
      private int width;
    
      @SerializedName("h")
      private int height;
    
      @SerializedName("d")
      private int depth;
    
      // Methods removed for brevity
    }
  • 2.@Expose注記
  • 注釈は、フィールドがシーケンス化または逆シーケンス化できるかどうかを指定することができ、デフォルトでは、両方がサポートされている(true).

  • 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;
    }
  • 注意が必要なのはbuilder.ExcludeFieldsWithoutExposeAnnotation()メソッドは、この注釈を有効にします.
  •   final GsonBuilder builder = new GsonBuilder();
        builder.excludeFieldsWithoutExposeAnnotation();
        final Gson gson = builder.create();
  • 3.@Sinceと@Until注記
  • Sinceは「から」、Untilは「まで」を表します.いずれもこのフィールドに対して有効なバージョンです.例えば,@Since(1.2)はバージョン1.2以降に有効であり,@Until(0.9)はバージョン0.9以前に有効であることを表す.

  • 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シーケンス化

  • 1シーケンス化スキーム1
  • は、上記の@SerializedName注記を使用します.

  • public class Book {
      private String[] authors;
    
      @SerializedName("isbn-10")
      private String isbn10;
    
      @SerializedName("isbn-13")
      private String isbn13;
      private String title;
      // , getter setter 
    
    }
  • シーケンス化スキーム2
  • JsonSerializerクラス
  • を利用

    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;
        }
    }
  • JsonSerializerはインタフェースであり、独自の
  • を提供する必要があります.
    public interface JsonSerializer {
    
    /**
     *Gson  T 
     *
     * @param T  Json , Book
     * @return  T JsonElement
     */
    public JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext context);
    }
  • まず上のコードでは、BookがオブジェクトであるJsonObjectタイプを作成するJsonElementオブジェクトを作成する必要があります.
  • final JsonObject jsonObject = new JsonObject();
  • その後、対応するフィールドのデータをjsonObjectに入力します.
  • jsonObject.addProperty...
    jsonObject.add...
  • ですので、最後に戻ったのはJsonElementタイプで、ここではjsonObjectに対応しています.JavaBean->JSONデータの変換が完了しました.
  • 同様に構成が必要であり、
  • .
    // 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逆シーケンス化

  • 1逆シーケンス化スキーム1
  • @SerializedName注釈
  • を使用
  • つまり私たちの実体クラスBookです.JAvaは
  • と書くことができます.
    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;
      }
    }
  • Gsonシーケンス化章と同様に、JSONデータの解析(逆シーケンス化)をエンティティクラスにする方法を分析します.
  • 上のJSONデータが{}カッコで囲まれていることがわかり、Jsonオブジェクトであることを意味します.まずfinal JsonObject jsonObject = json.getAsJsonObject()を通りますJsonElementをJsonObject
  • に変換
  • は、jsonObject.get("xxx").getAsString()の形式で対応するStringの値
  • を取得する.
  • jsonObject.get("xx").getAsJsonArray()を通過する.対応するjson配列を取得し、対応するフィールド値
  • を巡回する
  • 得られた値はsetterメソッドによってBookクラスに設定される.
  • は最終的にBookのオブジェクトインスタンスを返します.JSON->javaBeanの変換を完了するには、同様に構成
  • が必要です.
  • ローカルストリームからのJsonデータの読み出しについては、InputStreamReaderを使用して
  • を完了することができる.
    // 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);
      }