How to split two json String

Issue

I have a string but it contains two object like the following {"firstName":"A","lastName":"Z"}{"firstName":"B","lastName":"Y"}
I got this string as a response but I want to process it one by one, so how I should separate this one like {"firstName":"A","lastName":"Z"} and {"firstName":"B","lastName":"Y"}

Solution

Object mapper = new ObjectMapper();   
 List<YourClass> ls= ((ObjectMapper) mapper).readValue(
                    "[{"firstName":"A","lastName":"Z"},{"firstName":"B","lastName":"Y"}]",
                    new TypeReference<List<YourClass>>() {
                    });
//process list.

YourClass is mapping class of json input. Hope this is what you are looking for.

Edit:

As your input is received in {"firstName":"A","lastName":"Z"}{"firstName":"B","lastName":"Y"} fashion, then

String input = "{\"firstName\":\"A\",\"lastName\":\"Z\"}{\"firstName\":\"B\",\"lastName\":\"Y\"}";

String array[] = input.split("(?=\\{)|(?<=\\})");

System.out.println(array[0]);
System.out.println(array[1]);

Output:

{"firstName":"A","lastName":"Z"}
{"firstName":"B","lastName":"Y"}

Answered By – Ashish Patil

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published