简体   繁体   中英

How to handle multiple individual json response?

Actually I am doing some testing in which I am getting response from one of our endpoint which looks like multiple individual json objets and I need to convert them in such a form like a string or a single json object so that I can perform some action on them.

Json response Example:-

{"user_name":"testUser","email":"test@test.com"}
{"country":"Australia","Gender":"Male"}
{"type":"Customer_Account","membership":"Annual"}

Here the issue is I can not perform any operation until I convert it to some string or Json object.

And cannot control response as its coming from some third party application.

Any idea how to convert it using JavaScript to Java will be a great help.

If your objects are separated by line breaks, you can read the stream line by line, and parse each line that should be valid JSON.

Otherwise, you can detect the end of an object by keeping track of the level of nested braces (increment for { , decrement for } ).

Instead of parsing each object separately, you can also insert brackets and commas to form a valid JSON array, and then parse that array.

I think that your problem is in the source of the response, that is not a valid JSON. You can validate errors here: https://jsonlint.com/

Have you implemented the source of the JSON? If so you could make it a list of objects...

[{"user_name":"testUser","email":"test@test.com"},
{"country":"Australia","Gender":"Male"},
{"type":"Customer_Account","membership":"Annual"}]

If the source of the response is external (you can't modify it), it is possible to save the response into a String, then split the string into a list to iterate it to make the objects.

Hope this is somewhat helpful.

Join them with comma , and put result in brackets [] :

[
    {"user_name":"testUser","email":"test@test.com"},
    {"country":"Australia","Gender":"Male"},
    {"type":"Customer_Account","membership":"Annual"},
]

after that use can use JSONObject class or other related things

Split the JSONs using regex and keep it in an array:

 let text = '{"user_name":"testUser","email":"test@test.com"}{"country":"Australia","Gender":"Male"}{"type":"Customer_Account","membership":"Annual"}'; const myArray = text.split(/(?=[{])/g); let name = JSON.parse(myArray[0]).user_name; console.log(myArray[0]); console.log(name);

Now you can parse the strings as JSON.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM