From what you posted it looks similar to this since the outputs are separated with a nextline character. You could make use of it to split the string into an array of serialized json responses.
Then you could individually parse them into json objects.
Answer from humblerookie on Stack OverflowTry this :
String testV=new JSONObject(new String(responseBody)).toString();
or this if you need a JSONObject
JSONObject testV=new JSONObject(new String(responseBody));
The issue is that you declare a String variable and intent to store a JSONObjectinto it.
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;
JSONObject jsonObject = new JSONObject(IOUtils.toString(responseBody, StandardCharsets.UTF_8));
There is simpler approach to decode a ByteBuffer into a String without any problems, mentioned by Andy Thomas.
String s = StandardCharsets.UTF_8.decode(byteBuffer).toString();
EDIT (2018): The edited sibling answer by @xinyongCheng is a simpler approach, and should be the accepted answer.
Your approach would be reasonable if you knew the bytes are in the platform's default charset. In your example, this is true because k.getBytes() returns the bytes in the platform's default charset.
More frequently, you'll want to specify the encoding. However, there's a simpler way to do that than the question you linked. The String API provides methods that converts between a String and a byte[] array in a particular encoding. These methods suggest using CharsetEncoder/CharsetDecoder "when more control over the decoding [encoding] process is required."
To get the bytes from a String in a particular encoding, you can use a sibling getBytes() method:
byte[] bytes = k.getBytes( StandardCharsets.UTF_8 );
To put bytes with a particular encoding into a String, you can use a different String constructor:
String v = new String( bytes, StandardCharsets.UTF_8 );
Note that ByteBuffer.array() is an optional operation. If you've constructed your ByteBuffer with an array, you can use that array directly. Otherwise, if you want to be safe, use ByteBuffer.get(byte[] dst, int offset, int length) to get bytes from the buffer into a byte array.