使用 Gson 解析 Json 字符串给我错误

Parsing Json string by using Gson gives me error

我这辈子都想不通为什么会这样

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException:
Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

我可能已经阅读了超过 15 个 Whosebug 页面并尝试了一整天的一系列解决方案。

我有一个简单的 websocket 侦听器,每次从我的 websocket 服务器发送消息时 returns 一个字符串。

@Override public void onMessage(WebSocket webSocket, String text) {

    Log.d(TAG, "onMessage: Recieved: " + text);

}

它 returns 字符串:

{ 
   "camera_id":"e9502c54-927c-4639-a94f-8d03149c9c62",
   "posted_by":"14b07da5-1820-40db-8508 cc81261458aa",
   "posted_by_user":"david23",
   "message":"hello world"
}

我使用我的模型成功获得了每件商品 class

public class Message {

    private String camera_id;
    private String posted_by;
    private String posted_by_user;
    private String message;

    public String getMessage() {
        return message;
    }

    ... rest of methods
}

在我的 onMessage 侦听器中...

try{
    Gson gson = new Gson();
    Message message = gson.fromJson(text, Message.class);
    Log.d(TAG, "onMessage: " + message.getMessage());
}catch (Exception e){
    Log.d(TAG, "onMessage: Error: " + e);
}

我成功提取了消息密钥的字符串,但 gson 一直向我抛出此错误,我无法弄清楚原因。

Exception: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: 
Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

有些解决方案告诉我确认服务器发送的json是一个字符串。我已经两次,三次,无数次检查它是一个字符串。 甚至确保使用.. String.valueOf(text)

有人可以帮我查明错误的原因吗?

编辑 1:________________________________________________

使用 Roaim 的方法检查我返回的字符串是否包含 {},它说不包含,但我的日志告诉我包含。怎么会这样?

onMessage: Recieved: {"camera_id":"e9502c54-927c-4639-a94f-8d03149c9c62","posted_by":"14b07da5-1820-40db-8508-cc81261458aa","posted_by_user":"david23","message":"hello world"}

onMessage: hello world

Error: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String evan.com.websocketchatapplication.Message.getMessage()' on a null object reference

尝试 运行 邮递员上的 api 它会在 "Preview" 部分显示您从服务器获得的实际响应。

在您的消息中 class 替换 -

    private String camera_id;
    private String posted_by;
    private String posted_by_user;
    private String message;

与 -

    @SerializedName("camera_id")
    @Expose
    private String cameraId;
    @SerializedName("posted_by")
    @Expose
    private String postedBy;
    @SerializedName("posted_by_user")
    @Expose
    private String postedByUser;
    @SerializedName("message")
    @Expose
    private String message;

   /**
     * No args constructor for use in serialization
     *
     */
    public Message() {
    }

Exception: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

上述异常表明 GSON 期望字符串以 { 开头,但它得到了其他东西。

如果能保证字符串以{开头,那么上面的异常就没有了。让我告诉你如何确保,

public Message jsonToMessage(String json) {
    if (!json.contains("{") || !json.contains("}")) return null;

    String text = json.substring(json.indexOf("{"));
    JsonReader reader = new JsonReader(new StringReader(text));
    reader.setLenient(true);

    Gson gson = new Gson();
    return gson.fromJson(reader, Message.class);
}

Answer to the Edit1:

观察日志,onMessage() 方法似乎被调用了两次,其中一个有效 JSON 和一个无效文本,即 Message Processed in Lambda!。如果我没记错的话,那么简单地忽略 null Message 对象就可以了。顺便说一句,你可以检查我的方法返回null的文本来找出问题,

public Message jsonToMessage(String json) {
    if (!json.contains("{") || !json.contains("}")) {
        Log.d(TAG, "onMessage: jsonToMessage: " + json);
        return null;
    }

    ...
}