Arash GM
Arash GM

Reputation: 10395

Special Character in Json

i consume a webservice which i don't have enough control over it , so i have to parse what it returns! here is the parsing section :

        HttpResponse getResponse =  httpclient.execute(httpPost);  
        HttpEntity returnEntity = getResponse.getEntity();
        is = returnEntity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 128);
        StringBuilder sb = new StringBuilder();

        String line = null;
        while ((line = reader.readLine()) != null)
        {
            sb.append(line + "\n");
        }
        String result = sb.toString();
        result = result.replaceAll("^\"(.*)\"$","$1");
        JSONObject jObject = new JSONObject(result); //this line throws error

last line make an exception :

org.json.JSONException: Expected literal value at character 1 of {\r\n  \"xUserPW\": \"EmU7cU\"\r\n}

and the result String is :

{\r\n  \"xUserPW\": \"EmU7cU\"\r\n}

how can i prevent this exception?

Upvotes: 0

Views: 3424

Answers (3)

mmlooloo
mmlooloo

Reputation: 18977

Lets look at the json.org : http://json.org/

in that site the json defined in the side menu i just go along the path thats relevant to your problem:

object -> { members }    // each object replaces by { members }
members  -> pair      // each  members  replaces by pair
pair ->  string : value  // and so on ...
string -> "chars"
" chars " -> char chars
char -> any-Unicode-character-
        except-"-or-\-or-
        control-character  \"  \\  \/  \b \f \n \r \t \u four-hex-digits 

so your json must not begin by control characters, but i checked it and in other json validators it is ok for example in : http://www.freeformatter.com/json-validator.html but in json.org it is not. so just remove \r\n from begining and the end.

Upvotes: 1

Alexander Zhak
Alexander Zhak

Reputation: 9282

and the result String is : {\r\n \"xUserPW\": \"dStT0T\"\r\n}

This is not a valid json format. Is webservice returning you json? You cannot simply append \n to received data and convert it.

HttpResponse getResponse =  httpclient.execute(httpPost);  
    HttpEntity returnEntity = getResponse.getEntity();
    is = returnEntity.getContent();
    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 128);
    StringBuilder sb = new StringBuilder();

    String line = null;
    while ((line = reader.readLine()) != null)
    {
        sb.append(line);
    }
    JSONObject jObject = new JSONObject(sb.toString());

should not thow errors

Upvotes: 2

Jorgesys
Jorgesys

Reputation: 126563

JSONException: Expected literal value at character means that the .json returned must be invalid!

this is an invalid .json format:

{\r\n \"xUserPW\": \"dStT0T\"\r\n}

Upvotes: 1

Related Questions