如何访问“文本/纯文本”键中的数据

时间:2019-05-03 11:44:36

标签: java scala

这是我得到的json

{
    "id": 21,
    "code": "import scala.collection.JavaConversions._;import java.io.File;def getFileTree(f: File): Stream[File] =f #:: (if (f.isDirectory){ f.listFiles().toStream} else{ Stream.empty});getFileTree(new File(\"/home/datagaps/Downloads/\")).filter(_.getName.endsWith(\".json\")).foreach(println);",
    "state": "available",
    "output": {
        "status": "ok",
        "execution_count": 21,
        "data": {
            "text/plain": "/home/datagaps/Downloads/santanu.json\nimport scala.collection.JavaConversions._\nimport java.io.File\ngetFileTree: (f: java.io.File)Stream[java.io.File]\n"
        }
    },
    "progress": 1
}

这是我为访问字符串而编写的代码。

String output=getGETRequestResponse(uri).getJSONObject("output").getJSONObject("data").getString("text/plain");

org.json.JSONException: JSONObject["output"] is not a JSONObject.
    at org.json.JSONObject.getJSONObject(JSONObject.java:736)
    at com.datagaps.livyservice.service.LivyServerServiceImpl.getFilePaths(LivyServerServiceImpl.java:229)
    at com.datagaps.LivyProject.LivyServiceApplication.main(LivyServiceApplication.java:53)

在运行代码时,我遇到以下异常。

2 个答案:

答案 0 :(得分:0)

您可以尝试以下操作:

String output=getGETRequestResponse(uri).getJSONObject("output").getJSONObject("data").toString();
ObjectMapper mapper = new ObjectMapper();
Map<String, String> map = mapper.readValue(output, Map.class);
System.out.ptintln(map.get("text/plain"));

让我知道你能得到什么。

答案 1 :(得分:0)

您还可以执行以下操作:

        String data = "{\n" +
                "    \"id\": 21,\n" +
                "    \"code\": \"import scala.collection.JavaConversions._;import java.io.File;def getFileTree(f: File): Stream[File] =f #:: (if (f.isDirectory){ f.listFiles().toStream} else{ Stream.empty});getFileTree(new File(\\\"/home/datagaps/Downloads/\\\")).filter(_.getName.endsWith(\\\".json\\\")).foreach(println);\",\n" +
                "    \"state\": \"available\",\n" +
                "    \"output\": {\n" +
                "        \"status\": \"ok\",\n" +
                "        \"execution_count\": 21,\n" +
                "        \"data\": {\n" +
                "            \"text/plain\": \"/home/datagaps/Downloads/santanu.json\\nimport scala.collection.JavaConversions._\\nimport java.io.File\\ngetFileTree: (f: java.io.File)Stream[java.io.File]\\n\"\n" +
                "        }\n" +
                "    },\n" +
                "    \"progress\": 1\n" +
                "}";
//Here data is response which tou get from getGETRequestResponse(uri) so we can replace it like : String data = getGETRequestResponse(uri)

        JSONObject jsonRootObject = new JSONObject(data);
        final String value = jsonRootObject.getJSONObject("output").getJSONObject("data").getString("text/plain");
        System.out.println("text/plain value: " + value);