简体   繁体   中英

how to write jackson deserializer based on property in json

I want to write json deserializer on class Type so that when Type is deserialized from given json based on name it maps value (of type interface Being) to its current implementation based on some factory method that returns correct class name based on name, and populates remaining class without any explicit deserialization and without creating object of TigerBeing or HumanBeing explicitly using new.

I tried to use @jsonCreator but there i have to initialize entire HumanBeing or TigerBeing using new and passing all json in constructor. I need auto mapping for types further used as further pojo can be quite complex.

{type:[{
    "name": "Human",
    "value": { 
        "height":6,
        "weight":100,
        "languages":["spanish","english"]
    }
 },
{
"name":"Tiger",
"value":{
    "extinct":1,
    "found":["Asia", "America", "Europe", "Africa"]
}
}
]}

I have:

public class Type {
    String name;
    Being value;
}

public interface Being {
}

public class TigerBeing implements Being { 
    Integer extinct;
    String[] found;
}

public class HumanBeing implement Being {
    Integer height;
    Integer weight;
    String[] languages;
}
import java.io.IOException;

public class BeingDeserializer extends JsonDeserializer<Being> {

  @Override
  public Expertise deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonMappingException {

    JsonNode node = jp.getCodec().readTree(jp);
    String beingName = node.get("name").asText();
    JsonNode valueNode = node.get("value");
    BeingName beingByName = ExpertiseName.getBeingByName(beingName);
    if(beingByName ==null) {
      throw new JsonMappingException("Invalid Being " + beingName);
    }

    Being being =  JsonUtils.getObjectFromJsonNode(valueNode,
            ExpertiseFactory.getExpertise(beingByName).getClass());
    return being;
  }
}

In this way I was able to solve the above problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM