Java Gson:需要一个字符串,但是是 BEGIN_OBJECT

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41649731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:33:06  来源:igfitidea点击:

Gson: Expected a string but was BEGIN_OBJECT

javagson

提问by Student

I am trying to read a simple JSON response.

我正在尝试读取一个简单的 JSON 响应。

{ "response": "ok" }

{“响应”:“好的”}

Here is my code:

这是我的代码:

JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
        String response = null;
        boolean success = false;

        reader.beginObject();
        if (reader.hasNext())
        {
            String token = reader.nextName();

            if (token.equals("response")) {
                response = reader.nextString();
            }
            else {
                reader.skipValue();
            }
        }
        reader.endObject();
        reader.close();

But I am getting this error:

但我收到此错误:

Expected a string but was BEGIN_OBJECT

需要一个字符串,但是是 BEGIN_OBJECT

I don't understand what I am doing wrong. Can you help me?

我不明白我做错了什么。你能帮助我吗?

采纳答案by Lyubomyr Shaydariv

Your parser isfine. If the code snippet you provided really belongs to the exception stack trace you're getting, then I believe that the responseproperty of the JSON you're trying to parse has a value other than a string. For example,

解析器罚款。如果您提供的代码片段确实属于您获得的异常堆栈跟踪,那么我相信response您尝试解析的 JSON的属性具有字符串以外的值。例如,

{ "response": "ok" }

can be parsed by your parser just fine. However, the closest exception message you can get with your parser is a JSON similar to the one below:

可以被你的解析器解析就好了。但是,您可以使用解析器获得的最接近的异常消息是类似于以下内容的 JSON:

{ "response": {"status": "ok"} }

that should fail with something like

应该会失败,例如

Exception in thread "main" java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 16 path $.response

线程“main”中的异常 java.lang.IllegalStateException:需要一个字符串,但在第 1 行第 16 列路径 $.response 处为 BEGIN_OBJECT

Also note that Gson reports the problematic location at least in its latest versions (I tested it with Gson 2.5). Just make sure you're getting the expected input. If you believe the response must be in the format you mentioned, then just try to trace the input stream and find the differences. Tracing an input stream in its simplest but not the most efficient implementation, and you could have a slightly more efficient tracing reader like this:

另请注意,Gson 至少在其最新版本中报告了有问题的位置(我使用 Gson 2.5 对其进行了测试)。只要确保你得到了预期的输入。如果您认为响应必须采用您提到的格式,那么只需尝试跟踪输入流并找出差异即可。以最简单但不是最有效的实现方式跟踪输入流,您可以拥有一个更高效的跟踪阅读器,如下所示:

private static Reader traceReader(final Reader reader) {
    return new Reader() {
        @Override
        public int read(final char[] buffer, final int offset, final int length)
                throws IOException {
            final int read = reader.read(buffer, offset, length);
            if ( read != -1 ) {
                // or any other appropriate tracing output here
                out.print(new String(buffer, offset, read));
                out.flush();
            }
            return read;
        }

        @Override
        public void close()
                throws IOException {
            reader.close();
        }
    };
}

with:

和:

JsonReader reader = new JsonReader(traceReader(new InputStreamReader(in, "UTF-8")))

Then just re-check if you're really getting { "response": "ok" }.

然后只需重新检查您是否真的得到{ "response": "ok" }.