Archimedes
Archimedes

Reputation: 231

Blank space in JSON Value

I get a string in JSON format and I try to get the values. My method works fine, but if the value has a blank space in it, my method cracks up and it rains exceptions. Below is my code:

private String getValue(String jsonval)
{
    try
    {
        JSONObject jsonObject = new JSONObject(jsonval);
        return jsonObject.optString("id");
    }
    catch(JSONException e)
    {
        e.printStackTrace();
    }
    return null;
}

While this string works fine: {titleDE=Deutschland, id=10, titleEN=Germany} This one makes problems: {titleDE=Costa Rica, id=10, titleEN=Costa Rica} The exceptions says that the blank space is a unterminated object.

Upvotes: 1

Views: 25172

Answers (5)

\u200B can be added between the string "lets say \u200B this is string added here "---> this unicode (\u200B a) will be ignored and empty space added between say and this

Upvotes: 1

Satya
Satya

Reputation: 513

Try below JSON :

{titleDE:"Costa Rica", id:10, titleEN:"Costa Rica"}

You can put any json in http://jsonviewer.stack.hu/ and verify it.

Upvotes: 2

Anish Mittal
Anish Mittal

Reputation: 1182

Working:

Use:

{ "titleDE": "CostaRica", "id": 10, "titleEN": "Costa Rica" }

Space can be there. No issue. Just use : instead of =

Upvotes: 1

xenteros
xenteros

Reputation: 15852

Try the following JSON:

{"titleDE"="Costa Rica", "id"=10, "titleEN"="Costa Rica"}

Your problem is that a String is either a chain of characters without spaces (bad practice) or a chain of characters placed between " and ". If you want to use " in your String use escape character which is most often \.

Examples: "Deutchland", "Costa Rica", "He said \"whatever\" ".

Integer value can be without quotes, but it's a good practice to quote them and later cast those Strings to proper numeric types. When you cast 10 from JSON, some automatic parsers will cast it to int and some will cast to long. For this reason, it's better to cast it by yourself.

Upvotes: 1

Jimit Patel
Jimit Patel

Reputation: 4297

Send key and values in JSON string encased within double inverted quotes. Like this - "key"="string".

{"titleDE"="Deutschland", "id"=10, "titleEN"="Germany"}
{"titleDE"="Costa Rica", "id"=10, "titleEN"="Costa Rica"}

Also observe there is no blank space between key and = OR = and value. Integer/boolean values can be without quotes.

Upvotes: 2

Related Questions