【问题标题】:MalformedJsonException when parse a string in java在java中解析字符串时出现MalformedJsonException
【发布时间】:2019-12-26 11:58:42
【问题描述】:

我有这个代表学生实体的字符串:

{\"firstName\":\"Pirlog\",\"lastName\":\"Marcel\",\"year\":3,\"grupa\":\"B4\",\"accountId\":\"c9e4b165-8fdd-4ca2-974e-9b598ddb52bc\",\"id\":\"e577cf18-53bb-4e4e-bce2-b543f1d51f85\"}

Student 实体类是:

public class Student implements Serializable {
    private String firstName;
    private String lastName;
    private int year;
    private String grupa;
    private UUID accountId;
    private UUID id;

    public Student(){

    }

    public Student(String firstName, String lastName, int year, String grupa, String accountId, String id){
        this.id = UUID.fromString(id);
        this.firstName = firstName;
        this.lastName = lastName;
        this.year = year;
        this.grupa = grupa;
        this.accountId = UUID.fromString(accountId);
    }
}

为了解析字符串,我使用以下代码:

Gson g = new Gson();
String p = g.toJson(response1);
Student s = g.fromJson(p.substring(1, p.length() - 1), Student.class);
System.out.println(s.toString());

response1 是一个 httpresponse 的主体,它代表我的描述中的字符串。

例外:

Caused by: com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Expected name at line 1 column 2 path $.
    at com.google.gson@2.8.6/com.google.gson.Gson.fromJson(Gson.java:947)
    at com.google.gson@2.8.6/com.google.gson.Gson.fromJson(Gson.java:897)
    at com.google.gson@2.8.6/com.google.gson.Gson.fromJson(Gson.java:846)
    at com.google.gson@2.8.6/com.google.gson.Gson.fromJson(Gson.java:817)
    at Marcel/Marcel.controllers.uicontrollers.LoginScreenController.LoginFunction(LoginScreenController.java:42)

【问题讨论】:

    标签: java gson


    【解决方案1】:

    gson 错误表明您给它一个格式错误的 JSON 字符串,因此您需要检查的是您的 JSON。

    在这一行中,您将从 JSON 中删除大括号:

    Student s = g.fromJson(p.substring(1, p.length() - 1), Student.class);
    

    不要这样做;大括号是必需的。另一个问题可能是您的 JSON 中有一些反斜杠来转义双引号。也许这些是因为您将 JSON 移动到您的问题中的方式,但您应该在将字符串传递给 gson 之前将它们过滤掉。

    看看here,同样的问题也在这里讨论。

    【讨论】:

      【解决方案2】:

      替换这个

      Gson g = new Gson();
                  String p = g.toJson(response1);
                  Student s = g.fromJson(p.substring(1, p.length() - 1), Student.class);
                  System.out.println(s.toString());
      

      Gson g = new Gson();
              Reader reader = new StringReader(response1);
              Student s = g.fromJson(reader, Student.class);
              System.out.println(s.toString());
      

      【讨论】:

      • 解释一下会很有帮助,以防万一有人想真正学习一些东西,而不仅仅是从互联网上复制和粘贴一些代码。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 1970-01-01
      • 2020-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多