json for_0">最近看到有个同事在遍历json 数组的时候,用for循环写了一层有一层,那么是否有简便的写法呢?当然有了,下面就有用流的行驶,优雅的遍历数组,获取我们想要的数据
public static void main( String[ ] args) {
String structure = "[{\" key\" :\" 111\" ,\" isRequired\" :true,\" isNumber\" :true,\" isFixed\" :true},{\" key\" :\" 2\" ,\" isFixed\" :true},{\" key\" :\" 3\" ,\" isNumber\" :true},{\" key\" :\" 4\" ,\" isRequired\" :true}]" ;
JSONArray json Array;
try {
json Array = JSON.parseArray( structure) ;
} catch ( JSONException e) {
System.err.println( "Invalid JSON format: " + e.getMessage( )) ;
return ;
}
List< String> unitList = Optional.ofNullable( json Array)
.orElse( new JSONArray( ))
.stream( )
.filter( item -> item instanceof JSONObject)
.map( item -> {
JSONObject json Object = ( JSONObject) item;
String key = json Object.getString( "key" ) ;
return key;
} )
.collect( Collectors.toList( )) ;
System.out.println( unitList) ;
}