JSON 陣列,每個物件含 `code`, `name`, `type`, `categories` (子陣列)。需篩選 `type == "2"` (電費繳納) 的物件,取其 `categories` 所有元素。
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class JsonFilterDemo {
public static void main(String[] args) {
String jsonStr = "[{\"code\":\"I1_5200\",\"name\":\"移動繳費\",\"type\":\"4\",...}, ...]"; // 原始長字串
JSONArray array = JSON.parseArray(jsonStr);
for (int i = 0; i < array.size(); i++) {
JSONObject obj = array.getJSONObject(i);
String type = obj.getString("type");
if ("2".equals(type)) { // 目標 type
JSONArray categories = obj.getJSONArray("categories");
for (int j = 0; j < categories.size(); j++) {
JSONObject cat = categories.getJSONObject(j);
System.out.println("code: " + cat.getString("code"));
System.out.println("name: " + cat.getString("name"));
// 可進一步封裝為 DTO List
}
break; // 假設 type 唯一,找到即跳出
}
}
}
}
List result = JSON.parseArray(jsonStr, JSONObject.class).stream()
.filter(o -> "2".equals(o.getString("type")))
.findFirst()
.map(o -> o.getJSONArray("categories"))
.map(arr -> arr.toJavaList(Category.class))
.orElse(Collections.emptyList());
建議:專案已用 FastJSON 繼續用;新專案優先 Jackson 或 Gson,避開 FastJSON 歷史安全漏洞。