@JsonSubType Default Type If Not Matched.

5,403 views
Skip to first unread message

Gerald Wiltse

unread,
Aug 19, 2016, 1:59:37 PM8/19/16
to jackson-user
Question: Is there a way to specify a default subtype if there is not a specific match in the subtypes list?  

I'm new to Jackson and a novice developer, and I'm still struggling a bit with the basics of the annotations.  In my use case, the API i'm reading from has at least 20 or 30 "Resource Types", and more will be added regularly. Currently, I am aware of 3 or 4 types that have unique fields and need to be cast to a special subtype for that. However, if it's not one of a few special types, then it should just be cast as the GenericResource type.  In summary, it's impossible to maintain a comprehensive list of the generic subtypes I might get, so I just want to maintain the list of exceptional subtypes. 

Here's my example, I'm quite sure the "type = "*"" won't work, but maybe there's something similar? 

Also, the example might not even be using the annotations properly. Please me correct if wrong.

@JsonSubTypes({
       
@JsonSubTypes.Type(value = StorageResource.class, type = "Microsoft.Storage/storageAccounts"),
       
@JsonSubTypes.Type(value = GenericResource.class, type = "*") })

abstract class Resource {
   
public String id
   
public String name
   
public String type
   
public String location
}

public class GenericResource extends Resource {
}

public class StorageResource extends Resource {
   
public Sku sku
   
public String kind
   
public Tags tags
}

Sample JSON: 

{
   "value" : [{
"id" : "/subscriptions/98a83e18-54c4-402d-b38c-1d22aaf1cfa8/resourceGroups/NewTestRG/providers/Microsoft.Network/networkInterfaces/temptest425",
"name" : "temptest425",
"type" : "Microsoft.Network/networkInterfaces",
"location" : "westus2"
, {
"id" : "/subscriptions/98a83e18-54c4-402d-b38c-1d22aaf1cfa8/resourceGroups/NewTestRG/providers/Microsoft.Storage/storageAccounts/newtestrg731",
"name" : "newtestrg731",
"type" : "Microsoft.Storage/storageAccounts",
"sku" : {
"name" : "Standard_LRS",
"tier" : "Standard"
},
"kind" : "Storage",
"location" : "westus2",
"tags" : {}
}]
}

Tatu Saloranta

unread,
Aug 19, 2016, 2:11:12 PM8/19/16
to jackso...@googlegroups.com
Yes, this is what

    @JsonTypeInfo(...., defaultImpl = GenericImpl.class)

is for (assuming I understood question correctly).
That type is used if type id is missing, or does not map to anything (in case of type id to class mappings).

-+ Tatu +-


--
You received this message because you are subscribed to the Google Groups "jackson-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to jackson-user+unsubscribe@googlegroups.com.
To post to this group, send email to jackso...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages