Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何仅从以下JSON数组中提取结果?_Java_Json - Fatal编程技术网

Java 如何仅从以下JSON数组中提取结果?

Java 如何仅从以下JSON数组中提取结果?,java,json,Java,Json,我从API获得了以下格式的JSON数组: [{"confidence": "71.5579", "result": "Positive"}, {"confidence": "78.8726", "result": "Negative"}, {"confidence": "50.0000", "result": "Neutral"}, {"confidence": "57.7676", "result": "Neutral"}] 如何仅将结果部分(即“正”、“负”等)放入字符串数组中?或者

我从API获得了以下格式的JSON数组:

[{"confidence": "71.5579", "result": "Positive"}, 
{"confidence": "78.8726", "result": "Negative"}, 
{"confidence": "50.0000", "result": "Neutral"}, 
{"confidence": "57.7676", "result": "Neutral"}]

如何仅将结果部分(即“正”、“负”等)放入字符串数组中?或者只是得到正、负和中性的计数?我需要使用任何外部罐子吗?在eclipse中工作。

Java没有任何内置的JSON读取支持,因此您需要使用库。是一个流行的选择,您可以看到一些如何使用它的示例。

这取决于您所从事的项目类型,但如果您有权访问org.json包。它们是org.json.JSONObject和org.json.JSONArray类,您可以这样解析它们

    try {
        JSONArray jsonArray = new JSONArray("<string result from API>");
        int lenght = jsonArray.length();
        String[] results = new String[lenght];
        for (int i = 0; i < lenght; i++) {
            results[i] = jsonArray.getJSONObject(i).getString("result");
        }
    }
    catch (JSONException ex){
        ex.printStackTrace();
    }
试试看{
JSONArray JSONArray=新JSONArray(“”);
int lenght=jsonArray.length();
字符串[]结果=新字符串[长度];
对于(int i=0;i
您可以使用JSON库(如JsonSimple或GSON)将代码解析为JSON对象,然后根据需要获取值。阅读您使用的库的文档,了解解析和值操作是如何完成的。最后,您还可以通过执行基本字符串操作和字符串编辑来获得结果,但我不建议这样做,它违背了JSON的目的。@fillpant谢谢,我使用JSON库来实现它,是的,使用基本字符串匹配是我最初想到的,但这肯定比基本字符串匹配好。