我正在编写一个相对简单的消息应用程序,它将日志保存为JSON格式,并使用GSON库来解析这些日志。我从服务器加载一个JSON文件,并将其放入
Gson.toJsonTree()
作用我不确定这是预期的,但当我用
isJsonSomething()
函数(
isJsonObject
,
isJsonAray
,
isJsonNull
,
isJsonPrimitive
),
isJson基元
返回true,我无法将其解析为对象。这是我的JSON文件的内容:
{
"users": [
{
"picture": "",
"type": "user",
"name": "kroltan"
}
],
"description": "No description",
"messages": [
{
"content": "something",
"time": "2013-08-30 00:38:17.212000",
"type": "message",
"author": "someone"
}
],
"type": "channel",
"name": "default"
}
下面是用于将其解析为POJO的类:(CLEANUP注释是我从帖子中删除不相关代码的地方)
package com.example.testapp;
//CLEANUP: All needed imports
import com.example.testapp.data.*;
import com.google.gson.*;
public class JSONConverter {
public interface JsonTypeLoadedListener {
public void onSucess(JSONType jsonType);
public void onFailure(Exception e);
}
public static final String DATE_FORMAT = "dd-MM-yyyy HH:mm:ss.SSS";
public static final HashMap<String, Class<?>> JSON_TYPES = new HashMap<String, Class<?>>();
public JSONConverter() {
JSON_TYPES.clear();
JSON_TYPES.put("channel", Channel.class);
JSON_TYPES.put("user", User.class);
JSON_TYPES.put("message", Message.class);
}
public void loadFromURL(final URL url, final JsonTypeLoadedListener listener) {
new Thread(new Runnable() {
@Override
public void run() {
JsonObject result = null;
Gson gson = new GsonBuilder().setDateFormat(DATE_FORMAT).create();
if (url.getProtocol().equals("http")) {
try {
String content = //Loads from a server, omitted for clarity
result = gson.toJsonTree(content).getAsJsonObject();
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
listener.onFailure(e);
return;
}
} else if (url.getProtocol().equals("file")) {
try {
String content = //Loads from a file, omitted for clarity
result = gson.toJsonTree(content).getAsJsonObject();
br.close();
} catch (Exception e) {
e.printStackTrace();
listener.onFailure(e);
return;
}
}
listener.onSucess((JSONType) gson.fromJson(result, JSON_TYPES.get(result.get("type").getAsString())));
}
}, "URLLoader").start();
}
public JSONType loadFromString(String s) {
Gson gson = new Gson();
JsonObject result = gson.toJsonTree(s).getAsJsonObject();
return (JSONType) gson.fromJson(result, JSON_TYPES.get(result.get("type").getAsString()));
}
}
课程
Message
,
User
和
Channel
all继承自JSONType(一个自定义类,具有一个名为type的字段和一些实用程序方法),并包含上述JSON文件中存在的所有值。
当它到达时
gson.toJsonTree(content).getAsJsonObject()
,我在Logcat中得到了这个错误(为了清晰起见,省略了字符串,它只是完整的文件):
java.lang.IllegalStateException: Not a JSON Object: "String containing all the file with tabs represented as \t"