簡體   English   中英

在 gson 序列化期間省略 HashMap 名稱

[英]Omitting HashMap name during gson serialization

我希望使用 gson 序列化我的類,但我想省略哈希圖名稱。 gson可以做到嗎?

我曾嘗試編寫自己的 TypeAdapter,但地圖名稱仍寫為父對象。

我有一個看起來像的課程

public class myClass {
    @Expose
    public Long timestamp;
    @Expose
    public String id;
    @Expose
    public HashMap<String, someOtherClass> myMap = new HashMap<>();

    @Override
    public String toString() {
        Gson gson = new GsonBuilder()
                .excludeFieldsWithoutExposeAnnotation()
                .create();

        return gson.toJson(this);
    }
}

電流輸出:

{
  "timestamp": 1517245340000,
  "id": "01",
  "myMap": {
    "mapKey1": {
      "otherClassId": "100", // works as expected
    }
    "mapKey2": {
      "otherClassId": "101", // works as expected
    }
  }
}

我希望得到什么:

{
  "timestamp": 1517245340000,
  "id": "01",
  "mapKey1": {
      "otherClassId": "100", // works as expected
  },
  "mapKey2": {
      "otherClassId": "100", // works as expected
  }
}

編寫您自己的TypeAdapter 例如,參見 javadoc。

使用@JsonAdapter注釋指定它,或使用GsonBuilder注冊它。

@JsonAdapter(MyClassAdapter.class)
public class MyClass {
    public Long timestamp;
    public String id;
    public HashMap<String, SomeOtherClass> myMap = new HashMap<>();
}
public class MyClassAdapter extends TypeAdapter<MyClass> {
    @Override public void write(JsonWriter out, MyClass myClass) throws IOException {
        // implement the write method
    }
    @Override public MyClass read(JsonReader in) throws IOException {
        // implement the read method
        return ...;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM