Jackson JSZ Deserialisierung, ignorieren Wurzelelement von JSON

Wie zu ignorieren übergeordnetes tag von json??

Hier mein json

String str = "{\"parent\": {\"a\":{\"id\": 10, \"name\":\"Foo\"}}}";

Und hier ist die Klasse abgebildet werden, die aus json.

public class RootWrapper {
  private List<Foo> foos;

  public List<Foo> getFoos() {
    return foos;
  }

  @JsonProperty("a")
  public void setFoos(List<Foo> foos) {
    this.foos = foos;
  }
 }

Hier ist der test
public class JacksonTest {

@Test
public void wrapRootValue() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationConfig.Feature.UNWRAP_ROOT_VALUE, true);
    mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    String str = "{\"parent\": {\"a\":{\"id\": 10, \"name\":\"Foo\"}}}";

    RootWrapper root = mapper.readValue(str, RootWrapper.class);

    Assert.assertNotNull(root);
}

Bekomme ich die Fehlermeldung ::

 org.codehaus.jackson.map.JsonMappingException: Root name 'parent' does not match expected ('RootWrapper') for type [simple type, class MavenProjectGroup.mavenProjectArtifact.RootWrapper]

Fand ich die Lösung gegeben durch Jackson: Anmerkungen:

  (a) Annotate you class as below

  @JsonRootName(value = "parent")
  public class RootWrapper {

  (b) It will only work if and only if ObjectMapper is asked to wrap.
    ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationConfig.Feature.UNWRAP_ROOT_VALUE, true);

Job Gemacht!!

Andere Problemchen mit Jackson Art der Deserialisierung 🙁

wenn 'DeserializationConfig.Funktion.UNWRAP_ROOT_VALUE konfiguriert", es packen Sie alle jsons, obwohl meine Klasse nicht annotiert mit @JsonRootName(Wert = "rootTagInJson"), ist nicht weired.

Möchte ich Auspacken root-tag nur, wenn die Klasse annotiert mit @JsonRootName sonst nicht packen.

Also unten ist der Anwendungsfall für unwrap-root-tag.

  ###########################################################
     Unwrap only if the class is annotated with @JsonRootName.
  ############################################################

Habe ich eine kleine änderung in der ObjectMapper des Jackson-Quellcode und erstellt eine neue version der jar.
1. Platzieren Sie diese Methode in ObjectMapper

//Ash:: Wrap json if the class being deserialized, are annotated
//with @JsonRootName else do not wrap.
private boolean hasJsonRootName(JavaType valueType) {
    if (valueType.getRawClass() == null)
        return false;

    Annotation rootAnnotation =  valueType.getRawClass().getAnnotation(JsonRootName.class);
    return rootAnnotation != null;
}


    2. Edit ObjectMapper method :: 
    Replace 
       cfg.isEnabled(DeserializationConfig.Feature.UNWRAP_ROOT_VALUE)
    with
       hasJsonRootName(valueType)

    3. Build your jar file and use it.

InformationsquelleAutor der Frage Ash | 2012-01-12

Schreibe einen Kommentar