Livre de recettes pour la désérialisation Gson

Livre de recettes de désérialisation Gson

Dans ce livre de recettes, nous explorons les différentes manières deunmarshall JSON into Java objects, en utilisant les populairesGson library.

1. Désérialiser JSON en un seul objet de base

Commençons simplement - nous allons versunmarshall a simple json to a Java object – Foo:

public class Foo {
    public int intValue;
    public String stringValue;

    // + standard equals and hashCode implementations
}

Et la solution:

@Test
public void whenDeserializingToSimpleObject_thenCorrect() {
    String json = "{"intValue":1,"stringValue":"one"}";

    Foo targetObject = new Gson().fromJson(json, Foo.class);

    assertEquals(targetObject.intValue, 1);
    assertEquals(targetObject.stringValue, "one");
}

Lectures complémentaires:

Exclure des champs de la sérialisation dans Gson

Explorez les options disponibles pour exclure les champs de la sérialisation dans Gson.

Read more

Livre de recettes sur la sérialisation Gson

Apprenez à sérialiser des entités à l'aide de la bibliothèque Gson.

Read more

Jackson vs Gson

Guide rapide et pratique de la sérialisation avec Jackson et Gson.

Read more

2. Désérialiser JSON en objet générique

Ensuite, définissons un objet à l'aide de génériques:

public class GenericFoo {
    public T theValue;
}

Et unmarshall json dans ce type d'objet:

@Test
public void whenDeserializingToGenericObject_thenCorrect() {
    Type typeToken = new TypeToken>() { }.getType();
    String json = "{"theValue":1}";

    GenericFoo targetObject = new Gson().fromJson(json, typeToken);

    assertEquals(targetObject.theValue, new Integer(1));
}

3. Désérialiser JSON avec des champs inconnus supplémentaires en objet

Ensuite, désérialisons des json complexes contenant desunknown fields supplémentaires:

@Test
public void givenJsonHasExtraValues_whenDeserializing_thenCorrect() {
    String json =
      "{"intValue":1,"stringValue":"one","extraString":"two","extraFloat":2.2}";
    Foo targetObject = new Gson().fromJson(json, Foo.class);

    assertEquals(targetObject.intValue, 1);
    assertEquals(targetObject.stringValue, "one");
}

Comme vous pouvez le voir,Gson will ignore the unknown fields et correspond simplement aux champs dont il est capable.

4. Désérialiser JSON avec des noms de champs non correspondants en objet

Voyons maintenant comment Gson fait avec une chaîne json contenant des champs qui ne correspondent tout simplement pas aux champs de notre objetFoo:

@Test
public void givenJsonHasNonMatchingFields_whenDeserializingWithCustomDeserializer_thenCorrect() {
    String json = "{"valueInt":7,"valueString":"seven"}";

    GsonBuilder gsonBldr = new GsonBuilder();
    gsonBldr.registerTypeAdapter(Foo.class, new FooDeserializerFromJsonWithDifferentFields());
    Foo targetObject = gsonBldr.create().fromJson(json, Foo.class);

    assertEquals(targetObject.intValue, 7);
    assertEquals(targetObject.stringValue, "seven");
}

Notez que nous avons enregistréa custom deserializer - cela a pu analyser correctement les champs de la chaîne json et les mapper à nosFoo:

public class FooDeserializerFromJsonWithDifferentFields implements JsonDeserializer {

    @Override
    public Foo deserialize
      (JsonElement jElement, Type typeOfT, JsonDeserializationContext context)
      throws JsonParseException {
        JsonObject jObject = jElement.getAsJsonObject();
        int intValue = jObject.get("valueInt").getAsInt();
        String stringValue = jObject.get("valueString").getAsString();
        return new Foo(intValue, stringValue);
    }
}

5. Désérialiser le tableau JSON en tableau d'objets Java

Ensuite, nous allons désérialisera json array into a Java array des objetsFoo:

@Test
public void givenJsonArrayOfFoos_whenDeserializingToArray_thenCorrect() {
    String json = "[{"intValue":1,"stringValue":"one"}," +
      "{"intValue":2,"stringValue":"two"}]";
    Foo[] targetArray = new GsonBuilder().create().fromJson(json, Foo[].class);

    assertThat(Lists.newArrayList(targetArray), hasItem(new Foo(1, "one")));
    assertThat(Lists.newArrayList(targetArray), hasItem(new Foo(2, "two")));
    assertThat(Lists.newArrayList(targetArray), not(hasItem(new Foo(1, "two"))));
}

6. Désérialiser le tableau JSON en collection Java

Ensuite, un tableau jsondirectly into a Java Collection:

@Test
public void givenJsonArrayOfFoos_whenDeserializingCollection_thenCorrect() {
    String json =
      "[{"intValue":1,"stringValue":"one"},{"intValue":2,"stringValue":"two"}]";
    Type targetClassType = new TypeToken>() { }.getType();

    Collection targetCollection = new Gson().fromJson(json, targetClassType);
    assertThat(targetCollection, instanceOf(ArrayList.class));
}

7. Désérialiser JSON en objets imbriqués

Ensuite, définissons notre objet imbriqué -FooWithInner:

public class FooWithInner {
    public int intValue;
    public String stringValue;
    public InnerFoo innerFoo;

    public class InnerFoo {
        public String name;
    }
}

Et voici comment désérialiser une entrée contenant cet objet imbriqué:

@Test
public void whenDeserializingToNestedObjects_thenCorrect() {
    String json = "{\"intValue\":1,\"stringValue\":\"one\",\"innerFoo\":{\"name\":\"inner\"}}";

    FooWithInner targetObject = new Gson().fromJson(json, FooWithInner.class);

    assertEquals(targetObject.intValue, 1);
    assertEquals(targetObject.stringValue, "one");
    assertEquals(targetObject.innerFoo.name, "inner");
}

8. Désérialiser JSON à l'aide d'un constructeur personnalisé

Enfin, voyons comment forcer l'utilisation d'un constructeur spécifique lors de la désérialisation au lieu de la valeur par défaut - aucun constructeur d'arguments - en utilisantInstanceCreator:

public class FooInstanceCreator implements InstanceCreator {

    @Override
    public Foo createInstance(Type type) {
        return new Foo("sample");
    }
}

Et voici comment utiliser nosFooInstanceCreator dans la désérialisation:

@Test
public void whenDeserializingUsingInstanceCreator_thenCorrect() {
    String json = "{\"intValue\":1}";

    GsonBuilder gsonBldr = new GsonBuilder();
    gsonBldr.registerTypeAdapter(Foo.class, new FooInstanceCreator());
    Foo targetObject = gsonBldr.create().fromJson(json, Foo.class);

    assertEquals(targetObject.intValue, 1);
    assertEquals(targetObject.stringValue, "sample");
}

Notez qu'au lieu de null, leFoo.stringValue est égal àsample car nous avons utilisé le constructeur suivant:

public Foo(String stringValue) {
    this.stringValue = stringValue;
}

9. Conclusion

Cet article montre comment tirer parti de la bibliothèque Gson pourparse JSON input - en passant en revue les cas d'utilisation les plus courants pour les objets uniques et multiples.

L'implémentation de tous ces exemples et extraits de codecan be found in my github project - il s'agit d'un projet basé sur Eclipse, il devrait donc être facile à importer et à exécuter tel quel.