问题
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 Object
s 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 object
s:
{
"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