[英]How to convert Invalid JSON String to JSONObject in Java?
I have a string response like below which is a invalid json as it contains "obj13="
.I want to convert it to a JSONObject(JAVA)
and use it.Is there any good way to convert it to JSONObject without using String split operation. 我有一个如下所示的字符串响应,它是一个无效的json,因为它包含
"obj13="
。我想将其转换为JSONObject(JAVA)
并使用它。是否有任何好的方法可以在不使用String split操作的情况下将其转换为JSONObject 。
obj13={
players: [
{
name: "rocky",
place: "brazil",
age: "21",
},
{
name: "andy",
place: "New Zealand",
age: "23",
}
]
}
This is, of course, JavaScript, not JSON. 当然,这是JavaScript,而不是JSON。 If you can, I would go back to the service provider and ask for a JSON response.
如果可以,我将返回服务提供商并请求JSON响应。
If the format of the string is consistent, you could just use: 如果字符串的格式一致,则可以使用:
json=json.substring(json.indexof('=')+1);
and then parse the result. 然后解析结果。 Note that most good parsers should have an option to allow the keywords without quotes and to allow the extraneous commas ( mine does , but unfortunately for you it doesn't create JSONObject's but is of a lower level - it's designed to construct the data-structure of the caller's choice, which could be a JSONObject if that's what you wanted but you'd have to code it).
请注意,大多数优秀的解析器应该有一个选项,允许关键字不带引号,并允许多余的逗号( 我的允许,但不幸的是,它不会创建JSONObject,但级别较低-它旨在构造数据结构由调用者选择,如果您想要的话,可以是JSONObject,但您必须对其进行编码)。
If the result may or may not have the assignment, you may want to get a bit fancier and ensure that the non-whitespace characters before the '=' are valid for a JS identifier and the first non-whitespace after it is '{'. 如果结果可能分配也可能没有分配,您可能会有点儿幻想,并确保JS标识符在'='之前的非空白字符对于JS标识符有效,而在其后的第一个非空白字符为'{' 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.