【问题标题】:Is there a JSONParser method to parse the following string structure in Java?是否有 JSONParser 方法来解析 Java 中的以下字符串结构?
【发布时间】: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

标签: java json


【解决方案1】:

正如其他人在原始帖子下评论的那样,您的 JSON 字符串无效。因此,一种方法是直接解析给定的字符串,另一种方法是使无效的 JSON 字符串有效,然后由任何流行的 JSON 库解析。

方法一
如果您使用的是 JAVA 8,您可以使用 Stream 轻松检索 errorcode 的值,如下所示:

String errorCode = Arrays.asList(jsonStr.split(","))
    .stream()
    .filter(e -> e.contains("errorcode"))
    .findFirst()
    .get()
    .split(":")[1]
    .trim()
    .replace("'", "");
    System.out.println(errorCode);

方法二

JSONObject jsonObj = new JSONObject(jsonStr.replace("'", "\"").replace("\"\"", "\""));
String errorCode = jsonObj.get("errorcode").toString();
System.out.println(errorCode);

【讨论】:

  • 第三种方法是修复任何(或任何人)正在生成无效 JSON。
  • @Stephen C Ha,我完全同意你的看法!
  • 我得到这样的输出..{'errormessage': "'Unexpected", 'errorcode': '1'} 它给了我错误TypeError: can't convert {'errormessage': "'Unexpected", 'errorcode': '1'} to java.lang.String。帮我解决这个问题。
  • @LHCHIN 我还没有达到那个水平。我正在调用一个 py 脚本,它反过来给了我输出 {'errormessage': "'Unexpected", 'errorcode': '1'} 但在 java 中我无法将它作为 String 或 JSONObject。不知道如何在此处进行更改
  • @mannedear 你好,我认为你应该为这个例外创建另一个帖子。
猜你喜欢
  • 2021-05-08
  • 1970-01-01
  • 1970-01-01
  • 2013-05-26
  • 1970-01-01
  • 1970-01-01
  • 2011-08-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多