且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Google的Gson反序列化Bugzilla JSON时出现问题

更新时间:2023-02-18 19:10:47

Gson需要对原始问题中的情况进行自定义反序列化。以下是一个这样的例子。

Gson requires custom deserialization for the situation in the original question. Following is one such example.

input.json

[
  {
    "text":"some text"
  },
  {
    "text":{}
  }
]

Foo.java:

import java.io.FileReader;
import java.lang.reflect.Type;

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

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(String.class, new StringDeserializer());
    Gson gson = gsonBuilder.create();
    Thing[] things = gson.fromJson(new FileReader("input.json"), Thing[].class);
    System.out.println(gson.toJson(things));
  }
}

class Thing
{
  String text;
}

class StringDeserializer implements JsonDeserializer<String>
{
  @Override
  public String deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
      throws JsonParseException
  {
    if (json.isJsonPrimitive()) return json.getAsString();
    return "";
  }
}

输出:

[{"text":"some text"},{"text":""}]

使用 Thing.class 类型的自定义反序列化器当然会可能。这将有利于不为每个字符串添加额外的处理,但是您将被手动处理事情

Using instead a custom deserializer for the Thing.class type would of course be possible. This would have the benefit of not adding additional processing for every String, but then you'd be stuck with "manual" processing all of the other attributes of Thing.