Java – parsing JSON using gson, objects sometimes contain lists and sometimes objects

I'm using an API that sometimes contains a list of child objects:

{ 'obj' : { children: [ {id: "1"},{id: "2"} ] } }

I can parse this. No problem But if there is only one child, it will not return it as a list:

{ 'obj' : { children: {id: "1"} } }

My parser expects a list and then interrupts Does anyone have a suggestion on how to deal with this?

Solution

With gson, the only way I know how to handle this situation is to use a custom deserializer For example:

// outputs:
// [Container: obj=[ChildContainer: children=[[Child: id=1],[Child: id=2]]]]
// [Container: obj=[ChildContainer: children=[[Child: id=1]]]]

public class Foo
{
  static String json1 = "{\"obj\":{\"children\":[{\"id\":\"1\"},{\"id\":\"2\"}]}}";
  static String json2 = "{\"obj\":{\"children\":{\"id\":\"1\"}}}";

  public static void main(String[] args)
  {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERscoreS);
    gsonBuilder.registerTypeAdapter(Child[].class,new ChildrenDeserializer());
    Gson gson = gsonBuilder.create();
    Container container1 = gson.fromJson(json1,Container.class);
    System.out.println(container1);

    Container container2 = gson.fromJson(json2,Container.class);
    System.out.println(container2);
  }
}

class Container
{
  ChildContainer obj;

  @Override
  public String toString()
  {
    return String.format("[Container: obj=%1$s]",obj);
  }
}

class ChildContainer
{
  Child[] children;

  @Override
  public String toString()
  {
    return String.format("[ChildContainer: children=%1$s]",Arrays.toString(children));
  }
}

class Child
{
  String id;

  @Override
  public String toString()
  {
    return String.format("[Child: id=%1$s]",id);
  }
}

class ChildrenDeserializer implements JsonDeserializer<Child[]>
{
  @Override
  public Child[] deserialize(JsonElement json,Type typeOfT,JsonDeserializationContext context)
      throws JsonParseException
  {
    if (json instanceof JsonArray)
    {
      return new Gson().fromJson(json,Child[].class);
    }
    Child child = context.deserialize(json,Child.class);
    return new Child[] { child };
  }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>