[英]Omitting HashMap name during gson serialization
I am looking to serialize my class using gson but I would like to omit the hashmap name.我希望使用 gson 序列化我的类,但我想省略哈希图名称。 Is this possible with gson? gson可以做到吗?
I have tried writing my own TypeAdapter but the map name is still written as the parent object.我曾尝试编写自己的 TypeAdapter,但地图名称仍写为父对象。
I have a class which looks like我有一个看起来像的课程
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);
}
}
current output :电流输出:
{
"timestamp": 1517245340000,
"id": "01",
"myMap": {
"mapKey1": {
"otherClassId": "100", // works as expected
}
"mapKey2": {
"otherClassId": "101", // works as expected
}
}
}
What I am hoping to get :我希望得到什么:
{
"timestamp": 1517245340000,
"id": "01",
"mapKey1": {
"otherClassId": "100", // works as expected
},
"mapKey2": {
"otherClassId": "100", // works as expected
}
}
Write your own TypeAdapter
.编写您自己的TypeAdapter
。 See javadoc for example.例如,参见 javadoc。
Specify it with @JsonAdapter
annotation, or register it with GsonBuilder
.使用@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.