我正在尝试创建GSON类,但不确定如何处理这种情况。
根据API规范options
可以是列表值:[“一个”,“两个”]
或
可以是{“ value”:“ Label”}对的列表,以提供值标签
{
...
"options": ["one", "two", "three"],
}
OR
{
...
"options": [{"light": "Solarized light"}, {"dark": "Solarized dark"}],
}
答案 0 :(得分:2)
您可以将此字段映射到Map<String, String>
:
class Pojo {
@JsonAdapter(OptionsJsonDeserializer.class)
private Map<String, String> options;
// getters, setters, toString, other properties
}
基元列表意味着您只有值(无标签)。如果列出JSON Object
,则您的值带有标签。现在,您需要为给定的属性实现自定义反序列化器:
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();
}
}
简单用法:
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);
}
}
对于JSON object
秒:
{
"options": [
{
"light": "Solarized light"
},
{
"dark": "Solarized dark"
}
]
}
打印:
Pojo{options={light=Solarized light, dark=Solarized dark}}
有关基元列表:
{
"options": [
"one",
"two",
"three"
]
}
打印:
Pojo{options={one=null, two=null, three=null}}