简体   繁体   English

Json反序列化-预期为BEGIN_OBJECT,但为STRING

[英]Json deserialization - expected BEGIN_OBJECT but was STRING

This is the json I receive: 这是我收到的json:

{
    "data": "{\"keystring\": \"ag5zfmNvcGFya3NlcnZlcnIUCxIHQ29tbWVudBiAgICAusaBCgw\"}",
    "isSucceed": true,
    "error": ""
}

And this is the class and the code which is supposed to de-serialize it: 这是应该反序列化的类和代码:

public class ServerResponse {

    private boolean isSucceed;
    private String error;
    private JSONObject data;
}

//this is the code line responsible for deserialization, responseJson = the JSON above
ServerResponse response = gson.fromJson(responseJson, ServerResponse.class);

For some reason I get JsonSyntaxException: expected BEGIN_OBJECT but was STRING, which I guess is related to the data object ServerResponse holds, but I recieve it as a valid Json... 由于某种原因,我得到了JsonSyntaxException:预期为BEGIN_OBJECT,但为STRING,我猜这与ServerResponse持有的数据对象有关,但我将其作为有效的Json接收到。

Any ideas? 有任何想法吗?

Your data field 您的data字段

private JSONObject data;

is of type JSONObject . 类型为JSONObject But the value you receive for the corresponding key-value pair 但是您收到的对应键值对的值

"data": "{\"keystring\": \"ag5zfmNvcGFya3NlcnZlcnIUCxIHQ29tbWVudBiAgICAusaBCgw\"}",

is a JSON string. 是JSON字符串。 A JSON string is meant to map to a Java String . JSON字符串用于映射到Java String So it expected a JSON object, but received a JSON String. 因此,它期望使用JSON对象,但收到JSON字符串。

You can write and register your own TypeAdapter to make the conversion from JSON string to Java JSONObject . 您可以编写和注册自己的TypeAdapter来进行从JSON字符串到Java JSONObject的转换。 Or you can change your field to be of type String and convert it to a JSONObject when you need it. 或者,您可以将字段更改为String类型,并在需要时将其转换为JSONObject

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

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