java - Gson:如何解析可以是列表或字符串的多态值?

标签 java json gson

我需要解析一个包含一长串客户列表的 JSON 文件。在 JSON 文件中,每个客户可能有一个字符串形式的 id:

{
  "cust_id": "87655",
  ...
},

或者一些 id 作为数组:

   {
      "cust_id": [
        "12345",
        "45678"
      ],
      ...
    },

Customer 类如下:

public class Customer {

    @SerializedName("cust_id")
    @Expose
    private String custId;
    public String getCustId() {
        return custId;
    }

    public void setCustId(String custId) {
        this.custId = custId;
    }
}

我使用 Gson 解析 JSON:

Gson gson = new Gson()
Customers customers1 = gson.fromJson(json, Customers.class)

尝试解析数组时,它会失败,并显示 com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY

失败的原因很明确。

我的问题:在我无法更改 json 文件结构的情况下,处理这两种情况(当 id 是字符串和字符串数组时)的最佳方法是什么?

最佳答案

如果您想处理这两种情况,您可以使用自定义解串器。当然,您必须将“cust_id”变量更改为列表或数组。

主要:

String json1 = "{\"cust_id\": \"87655\"}";
String json2 = "{\"cust_id\": [\"12345\", \"45678\"]}";

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Customer.class, new CustomerDeserializer());
Gson gson = gsonBuilder.create();

Customer customer1 = gson.fromJson(json1, Customer.class);
System.out.println(customer1);

Customer customer2 = gson.fromJson(json2, Customer.class);
System.out.println(customer2);

客户

public class Customer {

    @SerializedName("cust_id")
    private List<String> custId;

    public List<String> getCustId() {
        return custId;
    }

    public void setCustId(List<String> custId) {
        this.custId = custId;
    }
}

客户反序列化器

public class CustomerDeserializer implements JsonDeserializer<Customer> {

@Override
public Customer deserialize(JsonElement jsonElement, Type typeOf, JsonDeserializationContext context) throws JsonParseException {
    Customer result = null;
    Gson gson = new Gson();

    try {
        // try to deserialize by assuming JSON has a list
        result = gson.fromJson(jsonElement, Customer.class);
    } catch (JsonSyntaxException jse) {
        // error here means JSON has a single string instead of a list

        try {
            // get the single ID
            String custId = jsonElement.getAsJsonObject().get("cust_id").getAsString();

            result = new Customer();
            result.setCustId(Arrays.asList(new String[] {custId}));
        } catch (Exception e) {
            // more error handling here
            e.printStackTrace();
        }
    }

    return result;
}

}

输出

Customer [custId=[87655]]
Customer [custId=[12345, 45678]]

关于java - Gson:如何解析可以是列表或字符串的多态值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43728659/

相关文章:

java - 如何使我的 java 程序能够持续运行并定期执行?

javascript - json 数据未在 Rails 中传递

java - Moshi 有像 Gson 这样的运行时类型适配器工厂吗?

java - 如何在 android 中循环 json 数组?

php - 尝试配置 ArrestDB。我认为我的数据源名称有问题

java - Gson 应为 BEGIN_ARRAY,但实际为 STRING

java - 复选框Click方法问题(类似xpath)-使用java的WebDriver

java - (Libgdx 1.6.1) BitmapFontCache.draw 由于索引越界而崩溃

java - Log4j LocationInfo Struts + Tomcat 缓慢

javascript - AngularJS JSON 格式