迭代JSON并从JSON获取字段

时间:2016-06-20 12:02:05

标签: java json loops

我尝试了不同的解决方案,但我无法遍历此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,但任何其他图书馆都可以。

3 个答案:

答案 0 :(得分:1)

您必须检查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);}

答案 1 :(得分:0)

试试这个

jObject = new JSONObject(contents.trim());
Iterator<?> keys = jObject.keys();

while( keys.hasNext() ) {
     String key = (String)keys.next();
    if ( jObject.get(key) instanceof JSONObject ) {

    }
}

答案 2 :(得分:0)

要直接访问字段,可以使用ObjectMappet(com.fasterxml.jackson)从JSON字符串创建Java对象。例如:

ObjectMapper mapper = new ObjectMapper();
MyClass myClass = mapper.readValue(jsonString, MyClass.class);