解析特定JSON与谷歌GSON
问题描述:
我需要如下解析其可限定的JSON项:解析特定JSON与谷歌GSON
{
...
"itemName": ""
...
}
或
{
...
"itemName": {
}
...
}
基本上,进料我从定义读取itemName
如一个空字符串,如果没有值,否则它是一个正常的JSON对象,我可以解析得很好。
我相信这是什么导致了我遇到的GSON错误,虽然我可能是错的。
我该如何解析包含如上所示的字段而不会导致GSON错误的JSON订阅源?或者我怎样才能抑制这个错误,并继续解析?
这里是logcat的:
ERROR/AndroidRuntime(32720): Caused by: com.google.gson.JsonParseException: Expecting object found: ""
我使用GSON包括在AdMob 4.0.4罐子
答
你需要实现自定义解串器这一点。以下是一个例子。
// output:
// {Outer: item=null}
// {Outer: item={Inner: value=foo}}
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
{
static String json1 = "{\"item\":\"\"}";
static String json2 = "{\"item\":{\"value\":\"foo\"}}";
public static void main(String[] args)
{
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Inner.class, new InnerDeserializer());
Gson gson = gsonBuilder.create();
Outer outer1 = gson.fromJson(json1, Outer.class);
System.out.println(outer1);
Outer outer2 = gson.fromJson(json2, Outer.class);
System.out.println(outer2);
}
}
class InnerDeserializer implements JsonDeserializer<Inner>
{
@Override
public Inner deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException
{
if (json.isJsonPrimitive())
{
return null;
}
return new Gson().fromJson(json, typeOfT);
}
}
class Outer
{
Inner item;
@Override
public String toString()
{
return String.format("{Outer: item=%s}", item);
}
}
class Inner
{
String value;
@Override
public String toString()
{
return String.format("{Inner: value=%s}", value);
}
}
这很容易被改为返回,而不是null
空Inner
实例,这取决于期望的,当然。