3

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.

4
  • What if there is a data in any field containing a backslash like: studentNumber: 2016\287 ? Still will you string replace? Commented Mar 6, 2019 at 5:36
  • 1
    use JSON parsing instead. It should create the object from the json string. stackoverflow.com/questions/2591098/how-to-parse-json-in-java Commented Mar 6, 2019 at 5:38
  • There won't be any data with backslash. main concern here is " before [ and after ]. Commented Mar 6, 2019 at 5:39
  • Answer of this question will help you. stackoverflow.com/questions/10308452/… Commented Mar 6, 2019 at 5:40

4 Answers 4

5

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);
Sign up to request clarification or add additional context in comments.

2 Comments

I did the same thing but because of extra \ and quotes before [ and after ] it's giving error. I removed \ using replace method but not able to remove quotes before [ and after ].
Below string works fine with my code: { "students" : [ {"studentId" : "A1","studentNumber" : "287","studentType" : "FullTime"} ] }
1

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

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

3 Comments

This is working fine. Just one question.. why do we add \\ before [ and ].
This is a hack that will likely break for nontrivial cases. I suspect the deserialized data will be wrong if anything in the student-objects contains json-escaped characters (e.g. quotes ", which will be doubly escaped) or "[ or "].
This should not have been the accepted answer
0

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

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

Comments

0
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.