gson 嵌套JSON的反序列化

cuxqih21  于 2023-03-29  发布在  其他
关注(0)|答案(1)|浏览(210)

我有以下JSON字符串

final String testInputString = "{\"actions\":[{\"actionName\":\"LOGIN\",\"actionAttributes\":{\"emailId\":\"abc@hello.com\",\"password\":\"password\"}},{\"actionName\":\"PERFORM\",\"actionAttributes\":{\"contentId\":\"gti\",\"contentType\":\"EVENT\"}}]}";

我正在尝试将其反序列化为DeviceActionList.class,请参见下面的类结构

@Data
@Builder
@AllArgsConstructor
public class DeviceActionList {
    List<DeviceAction> actions;
}

@Data
@Builder
@AllArgsConstructor
public class DeviceAction {
    @NonNull
    private ActionName actionName;
    private ActionAttributes actionAttributes;
}

public enum ActionName {
    LOGIN,
    PERFORM,
    WAIT,
    CLOSE_PLAYBACK
}

public class ActionAttributes {
}

@EqualsAndHashCode(callSuper = true)
@Data
@Builder
@AllArgsConstructor
public class LoginActionAttributes extends ActionAttributes {
    @NonNull
    private String emailId;
    @NonNull
    private String password;
}

@EqualsAndHashCode(callSuper = true)
@Data
@Builder
@AllArgsConstructor
public class PerformActionAttributes extends ActionAttributes {
    @NonNull
    private String contentId;
    @NonNull
    private String contentType;
}

我试过这个

objectMapper.readValue(testInputString, DeviceActionList.class)

然而,这会导致错误,它无法构造DeviceActionList的示例(不存在创建者,如默认构造函数):无法从Object值反序列化(没有基于委托或属性的Creator

gojuced7

gojuced71#

您提供的根JSON只包含一个testSuite字段,而不是DeviceActionList所期望的actions。您需要创建一个 Package 类,其中包含一个名为testSuite的字段,类型为DeviceActionList,并从那里反序列化JSON:

@AllArgsConstructor
public class TestSuite {
    DeviceActionList testSuite;
}

objectMapper.readValue(testInputString, TestSuite.class)

相关问题