1、利用Optional 提取Json中的某个字段的值, 本例子程序提取 sku 的值
import com.jd.fastjson.JSONArray;
import com.jd.fastjson.JSONObject;
import org.junit.Test;
import java.util.Optional;
/**
* @author: wangyingjie1
* @version: 1.0
* @createdate: 2017-09-19 16:31
*/
public class OptionalTest {
@Test
public void testOptionalGetValue() {
//利用Optional 提取Json中的某个字段的值, 本例子程序提取 sku 的值
String json = "{\n" +
" \"code\": \"0\",\n" +
" \"result\": \"Success\",\n" +
" \"data\": {\n" +
" \"totalCount\": 10,\n" +
" \"resultData\": [\n" +
" {\n" +
" \"sku\": 13346254358,\n" +
" \"name\": \"博世(BOSCH)机油滤清器 机油格 机滤 机油滤芯 新领驭 1.8T (09-10款)\",\n" +
" \"accyModelId\": 28489,\n" +
" \"cid1\": 6728,\n" +
" \"cid2\": 6742,\n" +
" \"cid3\": 11852,\n" +
" \"venderId\": 111655,\n" +
" \"brandId\": 5125,\n" +
" \"venderName\": \"上海硕泽实业有限公司\", \n" +
" \"modelIds\": null,\n" +
" \"carButlerCatIds\": [\n" +
" 2\n" +
" ]\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"foot\": {\n" +
" \"operationTime\": \"2017-09-20 11:18:10\",\n" +
" \"version\": \"1.0.0\",\n" +
" \"clientVersion\": null,\n" +
" \"client\": null,\n" +
" \"osVersion\": null\n" +
" }\n" +
"}";
Long sku = Optional.ofNullable(json)
.map(JSONObject::parseObject)
.map(jsonObject -> jsonObject.getJSONObject("data"))
.map(jsonObject -> jsonObject.getJSONArray("resultData"))
.flatMap(jsonArr -> convertJsonStrToJsonObjectStream(jsonArr))
.get();
System.out.println("sku============" + sku);
}
private Optional<Long> convertJsonStrToJsonObjectStream(JSONArray jsonArr) {
return jsonArr.stream()
.map(obj -> (JSONObject) obj)
.findFirst()
.map(obj -> obj.getLong("sku"))
;
}
}