admin管理员组

文章数量:1320616

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);

本文标签: How to deserialize json without property names with jackson libraryStack Overflow