【发布时间】:2020-04-26 01:44:45
【问题描述】:
我的 JSON 字符串输出如下。{'errorcode': '0', 'errormessage': "'success'", 'parsedoutput': [{'columnname': 'salary', 'columnalias': 'sal', 'tablename': 'employee', 'expression': 'salary', 'schemaname': 'prod', 'tablealias': 'e'}]}
我想解析这个字符串并获取值。在这里浏览了许多链接,但发现没有一个符合我的要求。所以发布为新问题,希望没有问题。
我在运行代码时遇到的错误:
Unexpected character (') at position 1.
at org.json.simple.parser.Yylex.yylex(Unknown Source)
at org.json.simple.parser.JSONParser.nextToken(Unknown Source)
at org.json.simple.parser.JSONParser.parse(Unknown Source)
at org.json.simple.parser.JSONParser.parse(Unknown Source)
at org.json.simple.parser.JSONParser.parse(Unknown Source)
at com.jsontostring.JSONToStringTest.main(JSONToStringTest.java:18)
我用来解析 json 字符串的 Java 代码..
public class JSONToStringTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
String jsonString = "{'errorcode': '0', 'errormessage': \"'success'\", 'parsedoutput': [{'columnname': 'salary', 'columnalias': 'sal', 'tablename': 'employee', 'expression': 'salary', 'schemaname': 'prod', 'tablealias': 'e'}]}";
try {
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject)parser.parse(jsonString);
System.out.println(json.get("errorcode"));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
【问题讨论】:
-
为什么双引号和单引号都成功?
-
jsonString = jsonString.replace("\'\"", "\"").replace("\"\'", "\"").replace('\'', '\"');然后解析。 -
@AliBeyit 理想情况下,双引号不应该在输出中显示,但我是这样理解的,我正在与分享给我的人核实。
-
你需要不同于 json 解析器的东西,因为你的输入不是 json
-
同意@codeflush.dev