21

I want to convert byte to JsonObject. I tried like this:

public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
    String testV=new JsonObject(new String(responseBody));
} 

But I am getting compiler error:

JsonObject cannot be applied to java.lang.String

How can I do this?

1
  • 1
    After the 2nd edit on testV data type from String to JsonObject, it is same as accepted answer and somehow confusing.
    – V-SHY
    Commented Dec 25, 2017 at 10:04

3 Answers 3

44

Try 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.

7
  • 1
    As there are so many available json libs. I believe in above solution you are referring to org.json lib
    – Arsal
    Commented Apr 20, 2018 at 1:47
  • How to import JSONObject? Commented Jan 31, 2019 at 6:44
  • 2
    Like any java import: import org.json.JSONObject; Commented Jan 31, 2019 at 7:14
  • This didn't work for me, it kept saying my JSON object does not start with a {, even when I added a trim() method to the String.
    – Azurespot
    Commented Oct 1, 2019 at 3:38
  • 1
    @Azurespot are you sure that you JSON content is valid? Commented Oct 1, 2019 at 7:10
2
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;

JSONObject jsonObject = new JSONObject(IOUtils.toString(responseBody, StandardCharsets.UTF_8));
1
  • How to import JSONObject? Commented Jan 31, 2019 at 6:43
-1
JSONArray testV = new JSONArray(new String(responseBody));
2
  • 1
    I need jsonobject. Not jsonArray Commented Apr 28, 2016 at 10:50
  • 2
    Add some clarification to your answer. Simply posting a code block is not considered a good answer on Stack Overflow. Commented Apr 28, 2016 at 11:52

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.