-1

I have a Json response of the following type -

{
    userName:"Jon Doe",
    country:"Australia"
}

My User class looks like this -

public class User{
    private String userName;
    private Country country;
}

GSON parsing fails with the following error:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 3 column 18 path $[0].country

Is there any way to tell GSON to parse country into the Country object with my current JSON response?

Abhinav Manchanda
  • 6,546
  • 3
  • 39
  • 46

1 Answers1

1

You can achieve this by registering a custom deserializer.

public static class Country {
    private String name;

    public Country(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Country{" + "name='" + name + '\'' + '}';
    }
}

public static class Holder {

    private String x;
    private Country y;

    public Holder() {
    }

    public void setX(String x) {
        this.x = x;
    }

    public void setY(Country y) {
        this.y = y;
    }

    @Override
    public String toString() {
        return "Holder{" + "x='" + x + '\'' + ", y=" + y + '}';
    }
}


@Test
public void test() {
    GsonBuilder gson = new GsonBuilder();
    gson.registerTypeAdapter(Country.class, (JsonDeserializer) (json, typeOfT, context) -> {
        if (!json.isJsonPrimitive() || !json.getAsJsonPrimitive().isString()) {
            throw new JsonParseException("I only parse strings");
        }
        return new Country(json.getAsString());
    });
    Holder holder = gson.create().fromJson("{'x':'a','y':'New Zealand'}", Holder.class);
    //prints Holder{x='a', y=Country{name='New Zealand'}}
    System.out.println(holder);
}
roby
  • 3,103
  • 1
  • 16
  • 14