简体   繁体   中英

Json deserialization - expected BEGIN_OBJECT but was STRING

This is the json I receive:

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

Any ideas?

Your data field

private JSONObject data;

is of type JSONObject . But the value you receive for the corresponding key-value pair

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

is a JSON string. A JSON string is meant to map to a Java String . So it expected a JSON object, but received a JSON String.

You can write and register your own TypeAdapter to make the conversion from JSON string to Java JSONObject . Or you can change your field to be of type String and convert it to a JSONObject when you need it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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