2016-06-17 20 views
5

Gibt es eine Möglichkeit, die Konfiguration SerializationFeature.WRAP_ROOT_VALUE als Annotation auf dem Stammelement anstatt ObjectMapper zu verwenden?SerializationFeature.WRAP_ROOT_VALUE als Annotation in jackson json

Zum Beispiel habe ich:

@JsonRootName(value = "user") 
public class UserWithRoot { 
    public int id; 
    public String name; 
} 

Mit ObjectMapper:

@Test 
public void whenSerializingUsingJsonRootName_thenCorrect() 
    throws JsonProcessingException { 
    UserWithRoot user = new User(1, "John"); 

    ObjectMapper mapper = new ObjectMapper(); 
    mapper.enable(SerializationFeature.WRAP_ROOT_VALUE); 
    String result = mapper.writeValueAsString(user); 

    assertThat(result, containsString("John")); 
    assertThat(result, containsString("user")); 
} 

Ergebnis:

{ 
    "user":{ 
     "id":1, 
     "name":"John" 
    } 
} 

Gibt es eine Möglichkeit, diese SerializationFeature als Anmerkung haben und nicht als eine Konfiguration auf der objectMapper?

Mit Abhängigkeit:

<dependency> 
    <groupId>com.fasterxml.jackson.core</groupId> 
    <artifactId>jackson-databind</artifactId> 
    <version>2.7.2</version> 
</dependency> 
+0

Vielleicht: http://stackoverflow.com/a/31158706/829571 Siehe auch: https://github.com/FasterXML/jackson-annotations/issues/33 – assylias

+0

@ assylias hat diese Antwort auch gesehen. Aber wissen Sie nicht, wie man es als niedrigerer Kamelfall bekommt. Brauche 'Benutzer' und nicht' Benutzer'. Nicht sicher, ob das möglich ist – Patrick

Antwort

6
import com.fasterxml.jackson.annotation.JsonTypeInfo; 
import com.fasterxml.jackson.annotation.JsonTypeName; 
import com.fasterxml.jackson.core.JsonProcessingException; 
import com.fasterxml.jackson.databind.ObjectMapper; 

public class Test2 { 
    public static void main(String[] args) throws JsonProcessingException { 
     UserWithRoot user = new UserWithRoot(1, "John"); 

     ObjectMapper objectMapper = new ObjectMapper(); 

     String userJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(user); 

     System.out.println(userJson); 
    } 

    @JsonTypeName(value = "user") 
    @JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.NAME) 
    private static class UserWithRoot { 
     public int id; 
     public String name; 
    } 
} 

@JsonTypeName und @JsonTypeInfo zusammen, um es möglich zu machen.

Ergebnis:

{ 
    "user" : { 
    "id" : 1, 
    "name" : "John" 
    } 
} 
+1

Vielen Dank dafür, ich kann nicht glauben, wie kompliziert es ist, nur eine Antwort zu wickeln. – Sean

+2

@Sean - So wahr, es ist komplex und braucht gewöhnungsbedürftig. Sie könnten sich etwas wie '@ JsonWrapper' oder' @ JsonRootValue' einfallen lassen, das den Namen des Wrappers trägt. – Isank

Verwandte Themen