我编写了代码以json格式解析来自服务器的响应。这是json
{
"2FrontSide": {
"back": ""
},
"3BackSide": {
"back": ""
},
"4FrontSide": {
"back": {
"type": "image",
"url": "http:\/\/www.abc.com\/sample_50.png"
}
}
}
并且解析此响应的代码是
Type collectionType = new TypeToken<Map<String,Map<String, VideosImages>>>(){}.getType();
Map<String,Map<String, VideosImages>> data = json.fromJson(resp, collectionType);
它给出了
10-23 17:50:25.500: W/System.err(29598): com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 33
10-23 17:50:25.500: W/System.err(29598): at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:180)
10-23 17:50:25.500: W/System.err(29598): at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:40)
10-23 17:50:25.505: W/System.err(29598): at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.read(MapTypeAdapterFactory.java:188)
10-23 17:50:25.505: W/System.err(29598): at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.read(MapTypeAdapterFactory.java:146)
10-23 17:50:25.505: W/System.err(29598): at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:40)
10-23 17:50:25.505: W/System.err(29598): at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.read(MapTypeAdapterFactory.java:188)
10-23 17:50:25.505: W/System.err(29598): at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.read(MapTypeAdapterFactory.java:146)
10-23 17:50:25.510: W/System.err(29598): at com.google.gson.Gson.fromJson(Gson.java:755)
10-23 17:50:25.510: W/System.err(29598): at com.google.gson.Gson.fromJson(Gson.java:721)
10-23 17:50:25.510: W/System.err(29598): at com.google.gson.Gson.fromJson(Gson.java:670)
10-23 17:50:25.515: W/System.err(29598): at com.putitout.buck.helpers.Network.fetchAllVideosAndImages(Network.java:47)
10-23 17:50:25.515: W/System.err(29598): at com.putitout.buck.VideoPlayback$2.run(VideoPlayback.java:462)
10-23 17:50:25.520: W/System.err(29598): at java.lang.Thread.run(Thread.java:856)
10-23 17:50:25.520: W/System.err(29598): Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 33
10-23 17:50:25.525: W/System.err(29598): at com.google.gson.stream.JsonReader.expect(JsonReader.java:339)
10-23 17:50:25.525: W/System.err(29598): at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:322)
10-23 17:50:25.530: W/System.err(29598): at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:168)
10-23 17:50:25.530: W/System.err(29598): ... 12 more
答案 0 :(得分:2)
为您的分配和收集实施InstanceCreator<Resp>
和JsonDeserializer<Resp>
。
在GsonBuilder
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter();
并在反序列化方法中解析你的json上下文。
@Override
public YourClass deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context){
}