-2

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"}

Guhan
  • 31
  • 1
  • 7

1 Answers1

1
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"}
user16320675
  • 135
  • 1
  • 3
  • 9
Ashish Patil
  • 4,428
  • 1
  • 15
  • 36
  • in array[] i got [{"firstName":"A","lastName":"Z"}, , {"firstName":"B","lastName":"Y"}] in array[0] i got {"firstName":"A","lastName":"Z"} and array[1] i got blank and array[2] i got {"firstName":"B","lastName":"Y"} – pratikpoponimb May 20 '22 at 08:38
  • Because you have extra `, ` in your input, can you please see what happens without it? – Ashish Patil May 20 '22 at 08:43
  • @Ashish Patil sure – pratikpoponimb May 20 '22 at 08:59
  • if i want array[1]= {"firstName":"B","lastName":"Y"} for that what should i do – pratikpoponimb May 20 '22 at 09:41
  • It means, your input is quite malformed & you have extra blank `,` within it. like `{"firstName":"A","lastName":"Z"}, , {"firstName":"B","lastName":"Y"} `. If you are receiving such malformed input, then that would be problem & you will receive even some other characters in between. Best you can do is ignore if array's element is blank & move on to next element. – Ashish Patil May 20 '22 at 09:45