Reputation: 513
All code below is simplified version. I have JSON structure:
{
"content" : {
"elements" : [ {
"type" : "simple"
},
{
"type" : "complex",
"content" : {
"elements" : [ {
"type" : "simple"
},
{
"type" : "simple"
},
{
"type" : "complex",
"content" : {
---- /// ----
}
} ]
}
} ]
}
}
I use Jackson lib for deserialization, and i am trying to implement a kind of "mix" custom with default deserializers. I want Element object creates using custom ElementDeserializer but for Content field inside use default. Unfortunately things like that:
@JsonDeserialize(using = StdDeserializer.class)
@JsonProperty
Content content;
isn't work =(
Here is my code now:
@JsonIgnoreProperties(ignoreUnknown = true)
public class Content {
@JsonProperty("elements")
ArrayList<Element> mElements;
}
@JsonDeserialize(using = ElementDeserializer.class)
@JsonIgnoreProperties(ignoreUnknown = true)
public class Element<T extends ElementType> {
@JsonProperty
Content content;
T mField;
public Element(T field) {
mField = field;
}
}
public class ElementDeserializer extends JsonDeserializer<Element> {
@Override
public Element deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
Element element = null;
JsonNode node = jp.getCodec().readTree(jp);
if ("simple".equals(node.get("type").textValue())) {
element = new Element(new SimpleField());
} else if ("complex".equals(node.get("type").textValue())) {
element = new Element(new ComplexField());
}
return element;
}
}
I will be grateful for some help!
Upvotes: 2
Views: 1126
Reputation: 131
Not sure whether it is mandatory for you to use a custom deserializer (for reasons not indicated in your post). If it is not, then you can do without one, using the default deserializers.
Here is how:
@JsonIgnoreProperties(ignoreUnknown = true)
public class TopObject {
@JsonProperty
public Content content;
public TopObject() {
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
public class Content {
@JsonProperty
public Element elements [];
public Content() {
}
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({
@Type(value = SimpleElement.class, name = "simple"),
@Type(value = ComplexElement.class, name = "complex")
})
public class Element {
public Element() {
}
}
public class SimpleElement extends Element {
public SimpleElement() {
}
}
public class ComplexElement extends Element {
@JsonProperty
public Content content;
public ComplexElement() {
}
}
Then unserialize the json data as a TopObject.class
Upvotes: 1