GSON identifying JSON Object as Primitive

独自空忆成欢 提交于 2019-12-25 02:39:15

问题


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. I load a JSON file from a server, and put it trough Gson.toJsonTree() function. 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. This is my JSON file's contents:

{
    "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)

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.

When it reaches gson.toJsonTree(content).getAsJsonObject(), I get this error in Logcat (string omitted for clarity, it's just the full file):

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

回答1:


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.

Btw I suggests you to get rid of Gson library and use directly the JSONObject provided in the android sdk. You can initialize it directly with the json string, as new JSONObject(content). :)



来源:https://stackoverflow.com/questions/18592762/gson-identifying-json-object-as-primitive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!