使用java使{"data":{"pictures":{},"skus":{"1714117164879904":{"effective_price":1980,"sku_id":7230624350863704000,"stock_num":21982},"1714117164879920":{"effective_price":1980,"sku_id":7230624350863688000,"stock_num":28982},"1714117164880896":{"effective_price":1980,"sku_id":7230624350863671000,"stock_num":49981},"1714117164880912":{"sku_id":7230624350863655000,"stock_num":29991,"effective_price":1980}},"specs":[{"name":"口味","spec_items":[{"id":"1714117164879904","name":"原味4袋共100g"},{"id":"1714117164879920","name":"烧烤味4袋共100g","select":true},{"id":"1714117164880896","name":"爆香孜然味4袋共100g"},{"id":"1714117164880912","name":"黑胡椒味4袋共100g"}]}],"error_code":0,"description":""},"extra":{"now":1683536909,"logid":"20230508170828AFC77E1BF34EA805F80A","error_code":0,"description":"","sub_error_code":0,"sub_description":""},"select":"烧烤味4袋共100g","item":{"cover":"https://p9-aio.ecombdimg.com/obj/ecom-shop-material/v1_inXJrDL_70834216251269942080421_ef096c3ab17f93308fa0a14ebd81da8e_sx_590268_www800-800","edit":true,"index":1}}中的spec_items只保留"select": true
时间: 2023-06-28 22:04:20 浏览: 149
可以使用以下代码来实现:
```java
import com.alibaba.fastjson.JSONObject;
public class Main {
public static void main(String[] args) {
String jsonStr = "{\"data\":{\"pictures\":{},\"skus\":{\"1714117164879904\":{\"effective_price\":1980,\"sku_id\":7230624350863704000,\"stock_num\":21982},\"1714117164879920\":{\"effective_price\":1980,\"sku_id\":7230624350863688000,\"stock_num\":28982},\"1714117164880896\":{\"effective_price\":1980,\"sku_id\":7230624350863671000,\"stock_num\":49981},\"1714117164880912\":{\"sku_id\":7230624350863655000,\"stock_num\":29991,\"effective_price\":1980}},\"specs\":[{\"name\":\"口味\",\"spec_items\":[{\"id\":\"1714117164879904\",\"name\":\"原味4袋共100g\"},{\"id\":\"1714117164879920\",\"name\":\"烧烤味4袋共100g\",\"select\":true},{\"id\":\"1714117164880896\",\"name\":\"爆香孜然味4袋共100g\"},{\"id\":\"1714117164880912\",\"name\":\"黑胡椒味4袋共100g\"}]}],\"error_code\":0,\"description\":\"\"},\"extra\":{\"now\":1683536909,\"logid\":\"20230508170828AFC77E1BF34EA805F80A\",\"error_code\":0,\"description\":\"\",\"sub_error_code\":0,\"sub_description\":\"\"},\"select\":\"烧烤味4袋共100g\",\"item\":{\"cover\":\"https://p9-aio.ecombdimg.com/obj/ecom-shop-material/v1_inXJrDL_70834216251269942080421_ef096c3ab17f93308fa0a14ebd81da8e_sx_590268_www800-800\",\"edit\":true,\"index\":1}}";
JSONObject jsonObject = JSONObject.parseObject(jsonStr);
JSONArray specItems = jsonObject.getJSONObject("data").getJSONArray("specs").getJSONObject(0).getJSONArray("spec_items");
for (int i = 0; i < specItems.size(); i++) {
JSONObject item = specItems.getJSONObject(i);
if (!item.getBooleanValue("select")) {
specItems.remove(i);
i--;
}
}
System.out.println(jsonObject.toJSONString());
}
}
```
这段代码使用了 fastjson 库来解析 JSON 字符串,并将 spec_items 中未被选中的元素移除。最后输出的 JSON 字符串中,只剩下了 "select": true 的元素。
阅读全文