Android 无法反序列化对象 - 预期为 BEGIN_OBJECT,但在第 1 行第 1 列处为 STRING

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24233564/
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-20 07:54:54  来源:igfitidea点击:

Cant deserialize object - Expected BEGIN_OBJECT but was STRING at line 1 column 1

androidgsonjson-deserialization

提问by Yosi199

First let me say, I have searched before posting, just cant find the answer.

先说一下,我发帖之前搜索过,就是找不到答案。

I'm having trouble de-serializing a JSON. It is a valid JSON (checked at http://jsonlint.com/) and it was produced with servicestack json serializer.

我在反序列化 JSON 时遇到问题。它是一个有效的 JSON(在http://jsonlint.com/ 上检查)并且它是用 servicestack json 序列化程序生成的。

I'm getting

我越来越

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1

Here is my JSON sent by the server:

这是服务器发送的我的 JSON:

{
    "artistName": "",
    "pathInfo": "C:\Users\Unknown\Desktop\Audio Sketches\Chill.mp3",
    "indexPos": 0,
    "messageType": "song"
}

How it being received:

接收方式:

{"artistName":"","pathInfo":"C:\Users\Unknown\Desktop\Audio Sketches\Chill.mp3","indexPos":0,"messageType":"song"}

Here is the object to hold it:

这是持有它的对象:

public class Song {

    private String artistName;
    private String albumName;
    private String titleName;
    private String pathInfo;
    private String indexPos;
    private String messageType;


    public Song() {
    }

采纳答案by Yosi199

Okay I end up finding the answer myself but thanks to all that supported and helped.

好的,我最终自己找到了答案,但感谢所有支持和帮助的人。

This is the code that received the JSON object and initiate the Deserialization using GSON.

这是接收 JSON 对象并使用 GSON 启动反序列化的代码。

 Map messageObjMap = new Gson().fromJson(message, Map.class);
 String type = messageObjMap.get("messageType").toString();

 switch (type) {
     case "song":
         try {
             Gson gson = new GsonBuilder().create();
             Song song = gson.fromJson(message, Song.class);
             ...
             ...
         } ...
     ...
 }

"message" was suppose to be the entire JSON. Instead it was a only a key parsed from the JSON and this is why the deserializtion didn't work. Hope that will help someone

“消息”应该是整个 JSON。相反,它只是从 JSON 解析出的一个键,这就是反序列化不起作用的原因。希望这会帮助某人

回答by Shereef Marzouk

String json = "{\"artistName\":\"\",\"pathInfo\":\"C:\Users\Unknown\Desktop\Audio Sketches\Chill.mp3\",\"indexPos\":0,\"messageType\":\"song\"}";
final JSONObject jsonObject = new JSONObject(json);
String path = jsonObject.getString("pathInfo");

I haven't used Gson but try this and let me know if it works

我没有用过 Gson,但试试这个,让我知道它是否有效