gpt4 book ai didi

java - 迭代 JSON 并从 JSON 中获取字段

转载 作者:行者123 更新时间:2023-11-30 07:18:52 27 4
gpt4 key购买 nike

我尝试了不同的解决方案,但无法迭代此 JSON 和/或获取直接的特定值。

有人可以帮忙吗:

  • 按顺序迭代所有字段。
  • 直接访问某些字段(例如,在获取此响应时,直接访问“packet-count”,其值等于3281)。

{"flow-node-inventory:flow":[{"id":"42","priority":10,"table_id":0,"opendaylight-flow-statistics:flow-statistics":{"packet-count":3281,"byte-count":317738,"duration":{"nanosecond":252000000,"second":3432}},"idle-timeout":10000,"cookie":31,"instructions":{"instruction":[{"order":0,"apply-actions":{"action":[{"order":0,"output-action":{"output-node-connector":"1","max-length":0}}]}}]},"match":{"ethernet-match":{"ethernet-source":{"address":"00:00:00:00:00:02"},"ethernet-destination":{"address":"00:00:00:00:00:01"}}},"hard-timeout":50000,"flags":""}]}

我尝试使用org.json,但任何其他库都可以。

最佳答案

您必须检查 JSON 对象的结构,并为您遇到的相应实体创建一个结构。例如,JSON 对象中的第一件事是一个数组,因此这是您应该关心的第一件事。将其想象为一个连续的封装。检查下面的代码以获取更多信息。

JSONObject jobj = new JSONObject(stringJson);
JSONArray flowNodeInv = jobj.getJSONArray("flow-node-inventory:flow");
for (int i = 0; i < flowNodeInv.length(); i++){
JSONObject segment = (JSONObject) flowNodeInv.get(i);
JSONObject stats = segment.getJSONObject("opendaylight-flow-statistics:flow-statistics");

int number = stats.getInt("packet-count");

System.out.println("packet-count: "+ number);}

关于java - 迭代 JSON 并从 JSON 中获取字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37922091/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com