使用Google的Gson反序列化Bugzilla JSON时出现问题 [英] Problem deserializing Bugzilla JSON using Google's Gson
问题描述
我在JSON中遇到了问题我从Bugzilla服务器回来,因为它有时会返回text:{},有时会返回text:blah blah blah。如果没有描述错误,Bugzilla会返回前者。我很神秘,为什么它不会回复为更合理的文本:但它确实就是这样。
I'm hitting a problem in JSON I'm getting back from a Bugzilla server because it sometimes returns "text" : {} and sometimes "text" : "blah blah blah". Bugzilla returns the former if no description was given for a bug. I'm mystified why it doesn't come back as the much more sensible "text" : "" but it does and that's it.
如果我有一个String Gson的目标对象中的文本,当它看到{}情况时它会反对,因为它表示它是一个对象而不是一个字符串:
If I have a String named text in the target object for Gson, it objects when it sees the {} case because it says that's an object and not a String:
Exception in thread "main" com.google.gson.JsonParseException: The
JsonDeserializer StringTypeAdapter failed to deserialized json object {} given
the type class java.lang.String
关于如何让Gson解析这个的任何建议?
Any suggestions on how I can make Gson parse this?
推荐答案
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
.
这篇关于使用Google的Gson反序列化Bugzilla JSON时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!