简体   繁体   中英

Is it possible to gson auto-map a JsonArray into a POJO

I have a pojo with 4 fields that I need to fill. The values are coming from a JsonArray of objects (nested within a larger JSON object) with many elements like so -

                           "res":[
                                    {"id":"irrelevant","val":"0"},
                                    {"id":"irrelevant","val":"N"},
                                    {"id":"irrelevant","val":"NO_THEFT"},
                                    {"id":"first_needed_field","val":"0"},
                                    {"id":"irrelevant","val":"N"},
                                    {"id":"second_needed_field","val":"33342"},
                                    etc etc etc
                                 ]

Is it possible to auto-map this JsonArray with the gson.fromJson() method?

I used the @SerializedName annotation to map the Pojo fields to match the id's but I have been unable to figure out how to transform the array to an object. None of my attempts have worked and while I have found many other gson questions on here and other people with the same errors, I have yet to find anyone intentionally attempting what I am trying.

This is rather vague, but I think I know what you want to do. The tip is to not do it.

Do use serialization and deserialization as provided by the Gson-library. But just iterate over the List<> and fill the object in a regular way.

Yes it is possible, however you are introducing interpretation into reflection . As you already mentioned you are mapping a bigger object, I can already envision the muddled code that comes from it.

You can do this using a custom TypeAdapter .

Lets say you have the following Pojo:

public class YourPojoClass {
  private String firstNeededField;
  private String secondNeededField;
  // Getters and setters...
}

You should declare the field res like this in the parent class:

public class YourParentClass {
  private YourPojoClass res;
  // Getters and setters...
}

Then you have to implement your custom TypeAdapter like this:

public class YourCustomTypeAdapter extends TypeAdapter<YourPojoClass> {
  @Override
  public YourPojoClass read(JsonReader in) throws IOException {
    YourPojoClass result = new YourPojoClass();
    Gson gson = new Gson();
    in.beginArray();
    while(in.hasNext()) {
      IdAndVal entry = gson.fromJson(in, IdAndVal.class);
      if (entry.getId() != null) {
        switch (entry.getId()) {
          case "first_needed_field":
            result.setFirstNeededField(entry.getVal());
            break;
          case "second_needed_field":
            result.setSecondNeededField(entry.getVal());
            break;
          default:
            break;
        }
      }
    }
    in.endArray();
    return result;
  }

  @Override
  public void write(JsonWriter out, YourPojoClass value) throws IOException {
    throw new UnsupportedOperationException("Not implemented");
  }

  private static class IdAndVal {
    private String id;
    private String val;

    public String getId() { return this.id; }
    public void setId(String id) { this.id = id; }

    public String getVal() { return this.val; }
    public void setVal(String val) { this.val = val; }
  }
}

All you have left to do now is to register this TypeAdapter using GsonBuilder to use it:

Gson gson = new GsonBuilder()
  .registerTypeAdapter(YourPojoClass.class, new YourCustomTypeAdapter())
  .create();

And you should be good to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM