Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

org.json.JSONException: Unterminated object at character 14

Tags:

java

json

android

The error message I got is:

org.json.JSONException: Unterminated object at character 14 of {address: yo test}

I think that I should escape the string, but in vain after trying all the method on StackOverflow.
Here is my code, thanks a lot for any help:

// src/Activity.java
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    try{
        String str = getString(R.string.data);
        JSONObject jsonObj = new JSONObject(str);
    }
    catch(Exception e){
        Log.d("iLoveDrinkActivity", e.toString());
        // org.json.JSONException: Unterminated object at character 14 of {address: yo test}
    }
}

And...

// res/strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="data">{"address": "yo test"}</string>
</resources>

If the "address" is something else like "test" or "yo" or "123", everything works fine. Thanks again!!

like image 494
iForests Avatar asked Nov 26 '11 13:11

iForests


2 Answers

Not directly related to the question, but I got this error when it was trying to parse malformed json. I was missing a comma between two properties. (Using gson)

like image 58
jgreen Avatar answered Sep 22 '22 02:09

jgreen


The only solution I can find (Android: Json string with spaces gives "Unterminated object at" exception) is to replace the quotes in your json with escaped quotes

<string name="data">{"address": \"yo test\"}</string>

Annoying though. Wonder if there's a better solution.

EDIT:

After a little more digging it looks like the culprit is the getString method which claims to

Return the string value associated with a particular resource ID. It will be stripped of any styled text information.

The stripping of styled text occurs in native code so I cannot see why it throws out the quotes, but looks like it does.

like image 38
I82Much Avatar answered Sep 18 '22 02:09

I82Much