例如,您有一个要转换为JSONObject的pojo列表.你有一个pojo列表.但是为了转换为JSONObject,您需要使用JSONObject put方法.
JSONObject personJson = new JSONObject();
for(Person person : personList){
personJson.put("firstName", person.firstName);
personJson.put("lastName", person.lastname);
...
}
Run Code Online (Sandbox Code Playgroud)
如果它只是我想做的一项操作,那么我就可以做到
personList.stream.map(personJson.put("firstName", person.firstName));
Run Code Online (Sandbox Code Playgroud)
JSONArray array=new JSONArray();
personList.stream().forEach(element ->
{
JSONObject personJson = new JSONObject();
personJson.put("firstName", element.firstName);
personJson.put("lastName", element.lastname);
array.add(personJson);
});
Run Code Online (Sandbox Code Playgroud)
此处提到的解决方案虽然有效,但它们是在流上下文之外对对象进行突变,应避免这种情况。
因此,.forEach()终止操作而不是使用return void。正确的方法是使用.map()它,正如其名称所说,将一个值映射到另一个值。在您的情况下,您要执行的第一个操作是将Person映射到JSONObject。第二个操作是一个reducer函数,您想在其中将所有JSONObject缩减为一个JSONArray对象。
public JSONArray mapListToJsonArray(List<Person> persons) {
List<JSONObject> jsonObjects = persons
.stream()
.map(person -> {
JSONObject json = new JSONObject();
json.put("firstName", person.getFirstName());
json.put("lastName", person.getLastName());
return json;
})
.collect(Collectors.toList());
return new JSONArray(jsonObjects);
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,JSONArray的json.org实现没有轻松合并两个数组的方法。因此,我没有将其简化为JSONArray,而是首先将所有JSONObjects收集为一个列表,然后从中创建一个JSONArray。
如果将lambda表达式替换为方法引用,则解决方案看起来更好。
public JSONArray mapListToJsonArray(List<Person> persons) {
List<JSONObject> jsonObjects = persons
.stream()
.map(this::mapPersonToJsonObject)
.collect(Collectors.toList());
return new JSONArray(jsonObjects);
}
public JSONObject mapPersonToJsonObject(Person person) {
JSONObject json = new JSONObject();
json.put("firstName", person.getFirstName());
json.put("lastName", person.getLastName());
return json;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7368 次 |
| 最近记录: |