Cuva
Cuva

Reputation: 335

Json Jersey Deserialize : Abstract Class

I'm trying to deserialize some JSON with Jersey/Jackson in Java.

Here is an example of my JSON

    {
        "text":"toto",
        "link":"titi",
        "items":[{
            "text":"toutou",
            "link":"tata",
            "items":[{
                "text":"toto2",
                "link":"toutou2",
                "data":"tonti",
            ]}
        ]}
    }

So what my Java model parts looks like this

public IItem {
    ...
}

public Item implements IItem {
    List<IItem> items;
    String text;
    String link;
    ...
}

public ItemData extends Item {
    String data;
    ...
}

Now, when i try to deserialize my JSON, object mapper doesnt know what concrete class to Use. How do I tell him this ? The thing is that I want an Item (with a list of Item (with a list of ItemData)).

I've though of only using one object containing all fields (text, link, data), but i'd prefer this type of design which appears better me. Do you think it's worth it ?

In reality I have more than one field that would replicate because JSON structure is a bit more complex, I've simplified it for sake of clarity.

Question2 : After that i need to serialise my objects again in JSON (first part is only for temporary development, I'll be filling objects from a JDBC driver later on), how can I tell jersey to only display one level at the time ?

i.e i request / I want the first level only, answer should be :

    {
        "text":"toto",
        "link":"titi",
        "items":[{
            "text":"toutou",
            "link":"tata",
        ]}
    }

and if i request /tata answer should be :

    {
        "text":"toutou",
        "link":"tata",
        "items":[{
            "text":"toto2",
            "link":"toutou2",
            "data":"tonti"
        ]}
    }

(Question is more about how hiding the second level in my first request, I do understand how to handle the second request).

Thanks,

Upvotes: 4

Views: 4120

Answers (1)

Perception
Perception

Reputation: 80613

If your using Jackson, it has a feature that allows for proper deserialization in these kind of cases (polymorphic list of items). You can use the @JsonTypeInfo annotation to indicate you want the object type to be included in the JSON, which will then be used to deserialize the correct instances. Here's an example:

@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class")
public IItem {
    // ...
}

This will add an attribute to each serialized representation of IItem, called @class, which Jackson will detect and use later on to deserialize the correct object instance.

Upvotes: 7

Related Questions