gaity
gaity

Reputation: 63

Remove double quotes from JSON String

I've below JSON string:

{ "students" : "[  {\"studentId\" : \"A1\",\"studentNumber\" 
 : \"287\",\"studentType\" : \"FullTime\"} ]"  }

In order to deserialize this string in java object, I've to remove \ which can be done using string replace method. Apart from that there are double quotes also just before [ and after ]. how do I remove these double quotes or allow them while deserializeing using Jackson.

Upvotes: 3

Views: 14656

Answers (4)

Bhukailas
Bhukailas

Reputation: 57

public class StringTypeSerializationAdapter extends TypeAdapter<String> {


public String read(JsonReader reader) {
    throw new UnsupportedOperationException();
}

public void write(JsonWriter writer, String value) throws IOException {
    if (value == null) {
        writer.nullValue();
        return;
    }
    writer.jsonValue(value);
}

}

above removes quotes from strings using GSON string adapter

Upvotes: 0

Tayyab Razaq
Tayyab Razaq

Reputation: 378

Like ObjectMapper, we also may use Gson for same purpose.

Gson gson = new Gson();
gson.fromJson(responseBody, Student.class);

Upvotes: 0

Abhishek Patyal
Abhishek Patyal

Reputation: 514

Try to replace "[ with [ and ]" with ]

json = json.replaceAll("\"\\[","[");
json = json.replaceAll("\\]\"", "]");

Upvotes: 1

Alok Dubey
Alok Dubey

Reputation: 419

You don't have to do it yourself, jackson will take care of it. Create a pojo class Student and you can write something like below:

ObjectMapper mapper = new ObjectMapper();
Student student = mapper.readValue(responseBody, Student.class);

Upvotes: 5

Related Questions