Java org.json.JSONException: 字符 14 处的未终止对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8278831/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
org.json.JSONException: Unterminated object at character 14
提问by iForests
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:
我认为我应该对字符串进行转义,但是在尝试了 StackOverflow 上的所有方法之后却徒劳无功。
这是我的代码,非常感谢您的帮助:
// 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!!
如果“地址”是“测试”或“哟”或“123”之类的其他内容,则一切正常。再次感谢!!
采纳答案by I82Much
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
我能找到的唯一解决方案(Android:带空格的 Json 字符串给出“未终止的对象在”异常)是用转义引号替换 json 中的引号
<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
经过更多的挖掘,看起来罪魁祸首是getString
声称的方法
Return the string value associated with a particular resource ID. It will be stripped of any styled text information.
返回与特定资源 ID 关联的字符串值。它将删除任何样式的文本信息。
The stripping of styled text occurs in native code so I cannot see why it throws out the quotes, but looks like it does.
样式文本的剥离发生在本机代码中,所以我不明白为什么它会抛出引号,但看起来确实如此。
回答by Rainbowbreeze
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.
否则 json 解析器将处理字符串{address: yo test},这不是有效的 json 字符串,而{address: "yo test"}是。
回答by jgreen
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)
与问题没有直接关系,但是在尝试解析格式错误的 json 时出现此错误。我在两个属性之间缺少逗号。(使用 gson)