在 Gson 反序列化器旁边使用 Room 持久性库中的 @Embedded

Mne*_*oee 6 java json pojo gson android-room

我使用 Google Room 持久性库将数据保存在数据库中。在 Room 中有一个注释(@Embedded):

您可以使用 @Embedded 注释来表示您想要分解为其在表中的子字段的对象。然后,您可以像查询其他单独列一样查询嵌入字段

@Entity
public class MyObject {

// nested class
public class GeneralInfo {

    public String ownerName;

    @PrimaryKey
    public long wellId;
}

@Embedded
public GeneralInfo generalInfo;

public long objectId;

// other fields
}
Run Code Online (Sandbox Code Playgroud)

我使用 Gson 从 REST API 反序列化 json 字符串,我希望 Gson 直接将GeneralInfo字段反序列化为MyObject字段。我怎样才能做到这一点?

我希望 GsonMyObject像这样反序列化 s:

{
    objectId : 1
    wellId : 1
    ownerName : "Me"
}
Run Code Online (Sandbox Code Playgroud)

不是这个

{
    generalInfo : {        
        wellId : 1
        ownerName : "Me"        
    } 
    objectId : 1
}
Run Code Online (Sandbox Code Playgroud)

除了使用还有什么办法吗JsonAdapter?我可以自己编写convertToJsonconvertFromJson但我想使用 Gson,最好使用注释告诉 Gson“不要将此嵌入对象反序列化为 jsonObject,将其字段插入其父 json 字段中”

jon*_*son 1

您可以使用自定义 TypeAdaptor:

public static void main(String[] args) {
    final MyObject myObject = new MyObject("Fardwark", 123, 9999L);
    final String json = gson.toJson(myObject);
    System.out.println(json);

    final MyObject myObject2 = gson.fromJson(json, MyObject.class);
    final String json2 = gson.toJson(myObject2);
    System.out.println(json2);
}

private static final Gson gson = new GsonBuilder()
        .registerTypeAdapter(MyObject.class, new MyTypeAdapter())
        .create();

private static final class MyTypeAdapter extends TypeAdapter<MyObject> {

    @Override
    public void write(JsonWriter jsonWriter, MyObject myObject) throws IOException {
        jsonWriter.beginObject()
                .name("ownerName").value(myObject.generalInfo.ownerName)
                .name("wellId").value(myObject.generalInfo.wellId)
                .name("objectId").value(myObject.objectId)
                .endObject();
    }

    @Override
    public MyObject read(JsonReader jsonReader) throws IOException {
        String ownerName = null;
        int wellId = 0;
        long objectId = 0;

        jsonReader.beginObject();;

        for (int i = 0; i < 3; ++i) {
            switch (jsonReader.nextName()) {
                case "ownerName":
                    ownerName = jsonReader.nextString();
                    break;
                case "wellId":
                    wellId = jsonReader.nextInt();
                    break;
                case "objectId":
                    objectId = jsonReader.nextLong();
                    break;
            }
        }

        jsonReader.endObject();

        return new MyObject(ownerName, wellId, objectId);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

{"ownerName":"Fardwark","wellId":123,"objectId":9999}
{"ownerName":"Fardwark","wellId":123,"objectId":9999}
Run Code Online (Sandbox Code Playgroud)