Marcel Pirlog
Marcel Pirlog

Reputation: 89

MalformedJsonException when parse a string in java

I have this string that represents a student entity:

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

The Student entity class is:

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

For parse the string I use this code:

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 is a httpresponse's body and it represents my string from description.

Exception:

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

Upvotes: 1

Views: 1284

Answers (2)

Seshidhar G
Seshidhar G

Reputation: 265

Replace this

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

with

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

Upvotes: 1

Alexander van Oostenrijk
Alexander van Oostenrijk

Reputation: 4754

The gson error indicates that you are giving it a malformed JSON string, so it's your JSON you need to examine.

In this line, you are removing braces from your JSON:

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

Don't do this; the braces are required. Another problem may be that you have some backslashes in your JSON to escape double quotes. Perhaps these are there because of the way you moved the JSON into your question, but you should filter them out before passing the string to gson.

Take a look here, as well, where the same problem is discussed.

Upvotes: 2

Related Questions