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

五迷三道 提交于 2021-02-07 08:49:27

问题


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.

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:

{
    "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() {
    }

回答1:


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.

 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




回答2:


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



来源:https://stackoverflow.com/questions/24233564/cant-deserialize-object-expected-begin-object-but-was-string-at-line-1-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!