java - 如何从 JSON 中提取在同一 JSON 中返回两个字符串的字段

标签 java json string

我的 JSON 看起来像这样

{
    "description":
    {
        "html": "A remote code execution vulnerability exists in the way that the scripting engine handles objects in memory in Microsoft Edge. ...",
        "text": "<p>A remote code execution vulnerability exists in the way that the scripting engine handles objects in memory in Microsoft Edge. ...</p>"
    }
}

我提取了字段描述,但它同时包含 html 和文本,而我只对文本字段感兴趣。

while (true)
{
    //Read
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
    String lines = null;
    StringBuilder stringBuilder = new StringBuilder();
    while ((lines = bufferedReader.readLine()) != null)
    {
        stringBuilder.append(lines);
    }
    bufferedReader.close();
    result = stringBuilder.toString();

    JSONParser parser = new JSONParser();
    JSONObject json2 = (JSONObject) parser.parse(result);
    if(methodType == MethodType.Retrieve_Vulnerability_info)
    {
        String scan_vuln_title= json2.get("title").toString();
        String scan_vuln_severityScore = json2.get("severityScore").toString();
        String scan_vuln_publishe_date = json2.get("published").toString();
        String scan_vuln_description = json2.get("description").toString();
        splunkdata.getScan().getList_of_found_Vulnerabilties().get(Vulnerability_id).setSeverityScore(scan_vuln_severityScore);
        splunkdata.getScan().getList_of_found_Vulnerabilties().get(Vulnerability_id).setVulnerability_title(scan_vuln_title);
        splunkdata.getScan().getList_of_found_Vulnerabilties().get(Vulnerability_id).setPublished_date(scan_vuln_publishe_date);
        splunkdata.getScan().getList_of_found_Vulnerabilties().get(Vulnerability_id).setDescription(scan_vuln_description);
        System.out.print("\n Rapid7 : Successful GET, vulnerabilities info of : "+ scan_vuln_title + " were retrieved" );
    }

有没有办法只提取文本内容?

最佳答案

不要提取到字符串,而是将描述提取为 JSON 对象。
所以你的代码看起来像这样,

JSONObject json3 = json2.getJSONObject("description")

那么,

String html = json3.get("html")
String text = json3.get("text")

另外,快速提醒一下,我正在使用 org.json

编辑1:因为您使用的是 simple.json

JSONObject json2 = (JSONObject) object.get("description");
String html = (String) json2.get("html");
String text = (String) json2.get("text");

关于java - 如何从 JSON 中提取在同一 JSON 中返回两个字符串的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56703632/

相关文章:

java - Rx 中的 groupBy、过滤器和内存泄漏

java - 如何使用 View 模型获取数组列表中的位置?

java - Apache HttpClient 和 PEM 证书文件

json - Angular 4 + Express 未在 Heroku 上启动

mysql - 如何删除MySQL JSON列中的键

ios - 使用嵌套对象和键为数组建模

ios - Swift: "nil while unwrapping an Optional value"不是零

java - 在 Controller 之外使用 Spring Data Rest RepositoryEntityLinks

javascript - 根据长度将字符串拆分为多个数组(javascript)

C# 正则表达式在字符串匹配后查找并删除文本