Jackson + Builder Pattern?

前端 未结 6 1801
春和景丽
春和景丽 2020-11-28 20:23

I\'d like Jackson to deserialize a class with the following constructor:

public Clinic(String name, Address address)

Deserializing the firs

6条回答
  •  眼角桃花
    2020-11-28 20:46

    I ended up implementing this using the @JsonDeserialize as follows:

    @JsonDeserialize(using = JacksonDeserializer.class)
    public class Address
    {...}
    
    @JsonCachable
    static class JacksonDeserializer extends JsonDeserializer
    { @Override public Address deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException { JsonToken token = parser.getCurrentToken(); if (token != JsonToken.START_OBJECT) { throw new JsonMappingException("Expected START_OBJECT: " + token, parser.getCurrentLocation()); } token = parser.nextToken(); Builder result = new Builder(); while (token != JsonToken.END_OBJECT) { if (token != JsonToken.FIELD_NAME) { throw new JsonMappingException("Expected FIELD_NAME: " + token, parser.getCurrentLocation()); } LocationType key = LocationType.valueOf(parser.getText()); token = parser.nextToken(); if (token != JsonToken.VALUE_STRING) { throw new JsonMappingException("Expected VALUE_STRING: " + token, parser.getCurrentLocation()); } String value = parser.getText(); // Our Builder allows passing key-value pairs // alongside the normal setter methods. result.put(key, value); token = parser.nextToken(); } return result.create(); } }

提交回复
热议问题