本文介绍了Gson:期望一个字符串,但是BEGIN_OBJECT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试阅读简单的JSON响应。 b
$ b

I am trying to read a simple JSON response.

以下是我的代码:

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:

我不明白我做错了什么。你可以帮我吗?

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

推荐答案

解析器很好。如果您提供的代码片段确实属于您获得的异常堆栈跟踪,那么我相信您试图解析的JSON的响应属性具有一个值除了一个字符串。例如,

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

{ "response": "ok" }

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

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:

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

应该会失败,例如

另请注意,Gson至少在最新版本中报告了有问题的位置(我用Gson 2.5测试过)。只要确保您获得预期的输入。如果您认为响应必须采用您提及的格式,那么只需尝试跟踪输入流并找出差异。使用最简单但并非最有效的实现追踪输入流,并且可以使用稍微更高效的追踪阅读器,如下所示:

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:

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

然后重新检查您是否确实收到 {response:ok}

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

这篇关于Gson:期望一个字符串,但是BEGIN_OBJECT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 11:46