问题描述:

In my application, imagine I can create an Animal Object :

public class Animal {

private int id;

private String food;

private String comment;

// Getter and setters

}

From somwhere in the app we create lot of Animal object and they are stored into the database.

Animal can also be created from JSON, so if I receive

{

"id":123456,

"food":"biscuit",

"comment":"black with white pows"

}

A new Animal will be created in database.

Now imagine we want to put that Animal into Zoo.

public class Zoo {

List<Animal> animals = new Arraylist<>();

// Getters and Setters

}

The Zoo can be constructed by Json. But here we don't want to receive the full Json for every Animal, but just their Id because they already exist into the database.

we will receive something like :

{

"animals": [

{

"id":123456

},

{

"id":987654

}

]

}

So we have two case, in the first case Animal are the root element of the Json we receive all the fields and store it into the database.

In the second case Animal can be into a list or just a child of another object and we receive only is Id to load it from the database during the deserialization.

So my question is, how from a custom deserializer, I can verify if the json I try to deserialize is a root Animal or a child animal ?

I'd like to write something like that :

public class ReferenceDeserializer extends JsonDeserializer<Animal> {

@Override

public Animal deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {

ObjectCodec oc = jp.getCodec();

JsonNode node = oc.readTree(jp);

if (I have a root Animal)

{

deserialize the full animal

} else if (I have a List or a Animal which is not a root object)

{

load the Animal from database with the id received

}

return myAnimal:

}

}

网友答案:

You can use @JsonIgnoreProperties(ignoreUnknown = true) annotation above the class definition. By this, only the id field of the Animal object will be populated and you don't have to use Custom deserializer.

相关阅读:
Top