0
String test ="{"abc":null}";
JSONObject testObj = new JSONObject(test);

giving error as abc is not a JSONObject. How can I convert this string to JSON Object?

In Actual implementation 'test' string i am reading from a file.. so escape sequence not added..!!

1
  • use this, String test ="{\"abc\":null}"; Commented Apr 24, 2017 at 12:37

2 Answers 2

1

The concatenation in your string is not alright. Is abc an object? or is it just the string abc?

String test = "{" + "abc" + ":null}";

but in the above case, you should simply do:

String test = "{abc:null}";

Or if abc is another defined String variable, say like this:

String abc = "awesomeText";
String test = "{" + abc + ":null}";

Or maybe you need those quotes from abc? use "\" to escape the quote character. Like this:

String test ="{\"abc\":null}";
Sign up to request clarification or add additional context in comments.

Comments

0

I made this test and it worked fine for me:

public static void main(String[] args) {
    BufferedReader br;
    try {
        br = new BufferedReader(new FileReader("C:\\test.json"));

        String currentLine;
        while ((currentLine = br.readLine()) != null) {
            JSONObject testObj = new JSONObject(currentLine);
            System.out.println(testObj);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

I tried many successful tests while playing with the content of the test.json file:

  1. {"abc":null}
  2. {'abc':null}
  3. {abc:null}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.