简体   繁体   English

用GSON稍微展平对象

[英]Slight flattening an object with GSON

My entities in Java look like 我在Java中的实体看起来像

{
    id: 123,
    name: "Some Name",
    someList: [1, 2, 3],
    data: {
        someDetail: "Whatever",
        anotherDetail: "And so on"
    }
}

ie, I moved some boring stuff into an @Embeddable Data data . 即,我将一些无聊的东西移到了@Embeddable Data data It's fine for use in Java, but I'm transferring the entities (without DTOs) via GSON and in Javascript, I'd strongly prefer a more flat structure 可以在Java中使用,但是我要通过GSON和Javascript传输实体(没有DTO),因此我强烈希望使用更扁平的结构

{
    id: 123,
    name: "Some Name",
    someList: [1, 2, 3],
    someDetail: "Whatever",
    anotherDetail: "And so on"
}

The only wanted change is treating the content of data as if it was in the main object directly, other parts should stay as they're. 唯一需要做的更改是将data内容视为直接位于主对象中,而其他部分则应保持原样。 The deserialization is needed, too. 也需要反序列化。

You could make a simple data class that transform the neccessary data points to single level from an input class. 您可以创建一个简单的数据类,将必要的数据点从输入类转换为单级。 Then you can export that flat class as json. 然后,您可以将该平面类导出为json。

class objectFlat {
    int id;
    String name;
    List<Integer> someList;
    String someDetail;
    public objectFlat(ObjectInput input) {
        this.id = input.id;
        this.name = input.name;
        this.someList = input.someList;
        this.someDetail = input.getData().someDetail;
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM