在 java 中解析字符串时出现 MalformedJsonException

MalformedJsonException when parse a string in java

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

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

学生实体 class 是:

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)

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

在这一行中,您要从 JSON:

中删除大括号
Student s = g.fromJson(p.substring(1, p.length() - 1), Student.class);

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

之前过滤掉它们

也看看here,那里讨论了同样的问题。

替换此

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());