Venkat Papana
Venkat Papana

Reputation: 4927

Text Must Begin With '{' Error parseing JSON in Java

I'm using org.json lib to parse my JSON string. My json string is from input stream. I'm reading the json string from input stream and passing it to JSONObject() constructor. But I'm getting the following exception:

[2011-08-28 23:42:52,235] main INFO - Task(): input = "{\"keyword\":\"xxxx"}" [2011-08-28 23:42:52,238] main ERROR - Task(): Exception: A JSONObject text must begin with '{' at 1 [character 2 line 1]

I guess the problem is with the extra double quotes," in my input. When I use new JSONObject("{\"keyword\":\"xxxx"}");, it is working fine.

++++ UPDATE ++++

Here is my json string reading code:

    try {
        in = new InputStreamReader(new BufferedInputStream(is));

        int c;
        while (true) {
            c = in.read();
            if (c == '\r' || c == '\n')
                break;
            requestLine.append((char) c);
        }

    } catch (Exception e) {
        logger.error("Task(): Exception: "+e.getMessage());
    }
    input = requestLine.toString();
    //input = "{\"keyword\":\"xxxx\"}"; //working fine
    logger.info("Task(): input = "+input);
    try{
        org.json.JSONObject json = new org.json.JSONObject(input);      
        keyword = json.getString("keyword");
    }catch(Exception e) {
        logger.error("Task(): Exception: "+e.getMessage());
    }


    logger.info("Task(): keyword = "+keyword);

Upvotes: 1

Views: 1124

Answers (1)

Venkat Papana
Venkat Papana

Reputation: 4927

I have solved this by eliminating the leading and trailing quotes by input = input.replaceAll("^\"|\"$", "");

Upvotes: 1

Related Questions