Java 8:如何编写 lambda 流以使用 JsonArray?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44595433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:37:45  来源:igfitidea点击:

Java 8: How to write lambda stream to work with JsonArray?

javalambdajava-8java-stream

提问by CrazySynthax

I'm very new to Java 8 lambdas and stuff... I want to write a lambda function that takes a JsonArray, goes over its JsonObjects and creates a list of values of certain field.

我对 Java 8 lambdas 和其他东西很陌生......我想编写一个 lambda 函数,它接受一个 JsonArray,遍历它的 JsonObjects 并创建某个字段的值列表。

For example, a function that takes the JsonArray: [{name: "John"}, {name: "David"}] and returns a list of ["John", "David"].

例如,一个函数接受 JsonArray: [{name: "John"}, {name: "David"}] 并返回 ["John", "David"] 的列表。

I wrote the following code:

我写了以下代码:

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class Main {
    public static void main(String[] args) {
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(new JSONObject().put("name", "John"));
        jsonArray.add(new JSONObject().put("name", "David"));
        List list = (List) jsonArray.stream().map(json -> json.toString()).collect(Collectors.toList());
        System.out.println(list);
    }
}

However, I get an error:

但是,我收到一个错误:

Exception in thread "main" java.lang.NullPointerException

线程“main”中的异常 java.lang.NullPointerException

DO you know how to resolve it?

你知道如何解决吗?

采纳答案by Eran

JSONArrayis a sub-class of java.util.ArrayListand JSONObjectis a sub-class of java.util.HashMap.

JSONArray是子类java.util.ArrayListJSONObject的是一个子类的java.util.HashMap

Therefore, new JSONObject().put("name", "John")returns the previous value associated with the key (null), not the JSONObjectinstance. As a result, nullis added to the JSONArray.

因此,new JSONObject().put("name", "John")返回与键 ( null)关联的先前值,而不是JSONObject实例。结果,null被添加到JSONArray.

This, on the other hand, works:

另一方面,这有效:

    JSONArray jsonArray = new JSONArray();
    JSONObject j1 = new JSONObject();
    j1.put ("name", "John");
    JSONObject j2 = new JSONObject();
    j2.put ("name", "David");
    jsonArray.add(j1);
    jsonArray.add(j2);
    Stream<String> ss = jsonArray.stream().map (json->json.toString ());
    List<String> list = ss.collect (Collectors.toList ());
    System.out.println(list);

For some reason I had to split the stream pipeline into two steps, because otherwise the compiler doesn't recognize that .collect (Collectors.toList())returns a List.

出于某种原因,我不得不将流管道分成两步,否则编译器无法识别.collect (Collectors.toList())返回一个List.

The output is:

输出是:

[{"name":"John"}, {"name":"David"}]

回答by Ali Katkar

Yes, I recognized that result of put is being added to json array instead of json object. Should be like this.

是的,我认识到 put 的结果被添加到 json 数组而不是 json 对象。应该是这样的。

private static JSONObject getJson(String key, String value){
    JSONObject result = new JSONObject();
    result.put(key, value);
    return result;        
}

public static void main(String[] args) {
    JSONArray jsonArray = new JSONArray();

    jsonArray.add(getJson("name", "John"));
    jsonArray.add(getJson("name", "David"));

    List list = (List) jsonArray.stream()
                .map(json -> json.toString())
                .collect(Collectors.toList());
    System.out.println(list);
}

and output is now [{"name":"John"}, {"name":"David"}] like expected

和输出现在 [{"name":"John"}, {"name":"David"}] 像预期的那样

回答by Adrian

Try with IntStream.

尝试使用 IntStream。

List<String> jsonObject = IntStream
       .range(0,jsonArray.size())
       .mapToObj(i -> jsonArray.getJSONObject(i))
       .collect(Collectors.toList());