GSON可以是字符串数组或对象数组 [英] GSON can be an array of string or an array of object

查看:148
本文介绍了GSON可以是字符串数组或对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建GSON类,但不确定如何处理这种情况.

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

根据API规范, options 可以是列表值:[一个",两个"]或

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

可以是{"value":"Label"}对的列表,以提供值的标签

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"}],
}

推荐答案

您可以将此字段映射到 Map< String,String> :

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

class Pojo {

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

    // getters, setters, toString, other properties
}

基元列表意味着您只有值(无标签).如果是 JSON对象的列表,则您的值带有标签.现在,您需要为给定的属性实现自定义反序列化器:

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();
    }
}

简单用法:

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对象 s:

{
  "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}}

这篇关于GSON可以是字符串数组或对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆