简体   繁体   English

GSON将JSON对象识别为原始对象

[英]GSON identifying JSON Object as Primitive

I am writing a relatively simple messaging app that saves its logs in the JSON format, and I am using the GSON library to parse these. 我正在编写一个相对简单的消息传递应用程序,该应用程序将其日志保存为JSON格式,并且正在使用GSON库进行解析。 I load a JSON file from a server, and put it trough Gson.toJsonTree() function. 我从服务器加载JSON文件,并将其通过Gson.toJsonTree()函数放入。 I'm not sure this is expected, but when I test the result from the previous function with the isJsonSomething() functions ( isJsonObject , isJsonAray , isJsonNull , isJsonPrimitive ), isJsonPrimitive returns true, and I can't parse it into a object. 我不确定这是预期的,但是当我使用isJsonSomething()函数( isJsonObjectisJsonArayisJsonNullisJsonPrimitive )测试来自先前函数的结果时, isJsonPrimitive返回true,并且我无法将其解析为对象。 This is my JSON file's contents: 这是我的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"
}

And here is the class used to parse it into POJOs: (CLEANUP comments is where I've removed irrelevant code from the post) 这是用于将其解析为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()));
    }
}

The classes Message , User and Channel all inherit from JSONType (a custom class with a field called type and some utility methods) and contain all values present in the above mentioned JSON file. MessageUserChannel都继承自JSONType(一个自定义类,其字段称为type和一些实用程序方法),并包含上述JSON文件中存在的所有值。

When it reaches gson.toJsonTree(content).getAsJsonObject() , I get this error in Logcat (string omitted for clarity, it's just the full file): 当到达gson.toJsonTree(content).getAsJsonObject() ,我在Logcat中收到此错误(为清晰起见,省略了字符串,它只是完整的文件):

java.lang.IllegalStateException: Not a JSON Object: "String containing all the file with tabs represented as \t"

I'm guessing that the tabs are causing your issue. 我猜这些标签引起了您的问题。 Try to remove them with: 尝试使用以下方法删除它们:

content = content.replaceAll("\\s","")

this will simply clean your json string from any whitespace. 这将只是从任何空白中清除json字符串。

Btw I suggests you to get rid of Gson library and use directly the JSONObject provided in the android sdk. 顺便说一句,我建议您摆脱Gson库,直接使用android sdk中提供的JSONObject。 You can initialize it directly with the json string, as new JSONObject(content) . 您可以直接使用json字符串将其初始化为new JSONObject(content) :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM