Home » Android » java – org.json.JSONException: Unterminated object at character 14

java – org.json.JSONException: Unterminated object at character 14

Posted by: admin June 15, 2020 Leave a comment

Questions:

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!!

How to&Answers:

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.

Answer:

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)

Answer:

Use

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

Otherwise json parser will process the string {address: yo test}, that is not a valid json string, while {address: “yo test”} is.