Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Json root element only for some classes

I'm using dropwizard to create REST API. But I dont understand, how can I configure Jackson to exclude some classes from WRAP_ROOT_VALUE/UNWRAP_ROOT_VALUE features? Right now I get a post request with json body that doesn't include root element name:

{
   "identification": "dummyuser",
   "password":"dummypass"
}

This should map to java class LoginRequest:

public class LoginRequest {
    public String identidication;
    public String passwrd;
}

I also get requests for some types that include root element name:

{
    "user":{
        "id":12345,
        "name":"John Doe"
    }
}

This should be mapped to:

@JsonRootName("user")
public class User {
   ...
}

To get root element working I had to include:

    environment.getObjectMapper().configure(SerializationFeature.WRAP_ROOT_VALUE, true);
environment.getObjectMapper().configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);

but now it applies for all classes. This means that whenever login request comes in, server will throw an error because it expects to see root element name.

like image 433
jyriand Avatar asked May 17 '15 15:05

jyriand


1 Answers

Use JsonTypeName with JsonTypeInfo instead of JsonRootName:

@JsonTypeName("user")
@JsonTypeInfo(include= JsonTypeInfo.As.WRAPPER_OBJECT,use= JsonTypeInfo.Id.NAME)
public class User {
   ...
}

@JsonTypeName

Annotation used for binding logical name that the annotated class has. Used with JsonTypeInfo (and specifically its JsonTypeInfo.use() property) to establish relationship between type names and types.

@JsonTypeInfo

Annotation used for configuring details of if and how type information is used with JSON serialization and deserialization, to preserve information about actual class of Object instances. This is necessarily for polymorphic types, and may also be needed to link abstract declared types and matching concrete implementation.

like image 186
Raphael Amoedo Avatar answered Sep 20 '22 16:09

Raphael Amoedo