【问题标题】:Error de-serializing Set in JSON在 JSON 中反序列化 Set 时出错
【发布时间】:2017-07-19 11:17:52
【问题描述】:

我有一个用例,我必须对对象使用多态性,因为这些是来自第三方服务器的响应。 这是我的响应类之一:

@JsonTypeInfo(
        use = JsonTypeInfo.Id.CLASS,
        include = JsonTypeInfo.As.PROPERTY,
        defaultImpl = RiderUpdate.class,
        property = "@class")
@JsonIgnoreProperties(ignoreUnknown = true)
public class RiderUpdate implements Serializable {

    @JsonProperty("status")
    private RiderStatus riderStatus;
    private Location location;
    @JsonProperty("orderIds")
    private Set<Long> orderIds;

    @JsonProperty("createdAt")
    private DateTime updatedAt;
    @JsonProperty("trackedObjectId")
    private String riderId;

这是我的对象映射器配置

@Bean
    public ObjectMapper buildMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JodaModule()).setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"));
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.registerSubtypes(RiderUpdate.class, RiderStatus.class, Location.class);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
        return mapper;
    }

我用来序列化的映射器函数:

@Component
public class JsonUtils {

    @Autowired
    private ObjectMapper objectMapper;

    private static final Logger logger = Logger.getLogger(JsonUtils.class);


    public String serializeObject(Object object) throws IOException {
        return objectMapper.writeValueAsString(object);
    }

    public <T> T readObject(String source, Class<T> objectClass) {
        T result = null;
        try {
            result = objectMapper.readValue(source, objectClass);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }

我正在尝试解析以下字符串:

{\"orderIds\":[3961393],\"location\": {\"latitude\":28 , \"longitude\":77},\"createdAt\":\"2017-02-22T16:26:29.982+05:30\",\"trackedObjectId\":\"1\"}

我在解析时遇到 JSON 错误。:

Unexpected token (VALUE_NUMBER_INT), expected VALUE_STRING: need JSON String that contains type id (for subtype of java.util.Set)

请帮忙。谢谢。

【问题讨论】:

    标签: java json serialization spring-boot


    【解决方案1】:

    您需要将riderId 类型从String 更改为intlong

    private int riderId;
    

    数字到字符串的隐式转换是不可能的。这就是你得到错误的原因。虽然trackedObjectId的值在双引号之间似乎有一个数字,但是通过json引擎解析后会转换为数字。因此,实际上您的代码正在尝试为字符串分配一个数字。因为这是不可能的,所以您会遇到异常。

    【讨论】:

    • 但例外是说一些与set有关的东西。我将集合更改为数组,它开始工作。不过,我没有碰 RiderId。但我想把它当成一套来用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-10
    • 2016-06-22
    • 2019-12-08
    • 1970-01-01
    • 2020-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多