GSON can be an array of string or an array of object

試著忘記壹切 提交于 2021-01-28 12:04:27

问题


I'm trying to create a GSON class but not sure how to handle this case.

According to the API specifications options can be a list values: ["one", "two"] OR

can be a list of {"value": "Label"} pairs to provide labels for values

{
...
  "options": ["one", "two", "three"],
}

OR

{
...
  "options": [{"light": "Solarized light"}, {"dark": "Solarized dark"}],
}

回答1:


You can map this field to Map<String, String>:

class Pojo {

    @JsonAdapter(OptionsJsonDeserializer.class)
    private Map<String, String> options;

    // getters, setters, toString, other properties
}

List of primitives means that you have only values (without labels). In case of list of JSON Objects you have values with labels. Now, you need to implement custom deserialiser for given property:

class OptionsJsonDeserializer implements JsonDeserializer<Map<String, String>> {

    @Override
    public Map<String, String> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        if (json.isJsonArray()) {
            Map<String, String> map = new HashMap<>();
            JsonArray array = json.getAsJsonArray();
            array.forEach(item -> {
                if (item.isJsonPrimitive()) {
                    map.put(item.getAsString(), null);
                } else if (item.isJsonObject()) {
                    item.getAsJsonObject().entrySet().forEach(entry -> {
                        map.put(entry.getKey(), entry.getValue().getAsString());
                    });
                }
            });

            return map;
        }

        return Collections.emptyMap();
    }
}

Simple usage:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.annotations.JsonAdapter;

import java.io.File;
import java.io.FileReader;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class GsonApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        Gson gson = new GsonBuilder().create();

        Pojo pojo = gson.fromJson(new FileReader(jsonFile), Pojo.class);
        System.out.println(pojo);
    }
}

For JSON objects:

{
  "options": [
    {
      "light": "Solarized light"
    },
    {
      "dark": "Solarized dark"
    }
  ]
}

prints:

Pojo{options={light=Solarized light, dark=Solarized dark}}

For list of primitives:

{
  "options": [
    "one",
    "two",
    "three"
  ]
}

Prints:

Pojo{options={one=null, two=null, three=null}}


来源:https://stackoverflow.com/questions/56011652/gson-can-be-an-array-of-string-or-an-array-of-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!