最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to deserialize json without property names with jackson library? - Stack Overflow

programmeradmin2浏览0评论

A webservice call, which is out of my control, returns a json response in this format:

[1737189665,1.0001,2.1123,"some string"]

The json consists of the bare values, i.e. without any property names. I know the property names (timestamp, min, max, message) from the documentation of the webservice.

That json must be mapped into an object of type Result

@Data   // lombok
@Builder  // lombok
public class Result {
  Long timestamp;
  Double min;
  Double max;
  String message;
}

What is the best way to do the mapping with the jackson library? Why jackson? Because my application has already chosen jackson as library to handle json.

I have already a working solution with a custom deserializer, but I am not sure if this is really the best way. Is the CustomDeserializer really necessary?

My solution is to register a custom deserializer with the Result class:

@Data
@Builder
@JsonDeserialize(using = ResultDeserializer.class)
 public class Result {
    // ...
 }

The ResultDeserializer looks like this:

public class ResultDeserializer extends StdDeserializer<Result> {

    // serialVersionId and constructors omitted

    @Override
    public Result deserialize(JsonParser p, DeserializationContext ctx) throws IOException, JacksonException {

        JsonNode node = p.getCodec().readTree(p);
        Iterator<JsonNode> children = node.elements();
        
        return Result.builder()
            .timestamp(children.next().asLong();)
            .min(children.next().asDouble())
            .max(children.next().asDouble())
            .message(children.next().asText())
        .build();
    }
}

The mapping looks like this:

Object[] rawJson = "[1737189665,1.0001,2.1123,\"some string\"]"; // in reality retrieved from webservice

ObjectMapper mapper = new ObjectMapper();
Result result = mapper.convertValue(rawJson, Result.class);
发布评论

评论列表(0)

  1. 暂无评论