如何访问二维json数组?

时间:2017-11-29 14:59:58

标签: java json jsonparser

我正在使用java 我导入了

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

假设我有" freeBaggageAvailable"

 "freeBaggageAvailable" : [
    {
        "Y" : [{
                "*" : [{"num":1,"weight": 23,"price": 0}],
               "mc" : [{"num:":1,"weight" : 23,"price": 0}, {"num":2, "weight": 23,"price": 0}],
               "mp" : [{"num:":1,"weight" : 23,"price": 0}, {"num":2, "weight": 23,"price": 0}],
               "mmc" :[{"num:":1,"weight" : 23,"price": 0}, {"num":2, "weight": 32,"price": 0}]
              }],
         "C" : [{
                "*" : [{"num":1,"weight":32 ,"price": 0},{"num":1,"weight":32 ,"price": 0}],
               "mc" : [{"num:":1,"weight" : 32,"price": 0}, {"num":2, "weight": 32,"price": 0},{"num":3,"weight":32 ,"price": 0}],
               "mp" : [{"num:":1,"weight" : 32,"price": 0}, {"num":2, "weight": 32,"price": 0},{"num":3,"weight":32 ,"price": 0}],
               "mmc" :[{"num:":1,"weight" : 23,"price": 0}, {"num":2, "weight": 32,"price": 0}]
              }],

          "F" : [{
                "*" : [{"num":1,"weight":32 ,"price": 0},{"num":1,"weight":32 ,"price": 0}],
               "mc" : [{"num:":1,"weight" : 32,"price": 0}, {"num":2, "weight": 32,"price": 0},{"num":3,"weight":32 ,"price": 0},{"num":4,"weight":32 ,"price": 0}],
               "mp" : [{"num:":1,"weight" : 32,"price": 0}, {"num":2, "weight": 32,"price": 0},{"num":3,"weight":32 ,"price": 0},{"num":4,"weight":32 ,"price": 0}],
               "mmc" :[{"num:":1,"weight" : 23,"price": 0}, {"num":2, "weight": 32,"price": 0},{"num":4,"weight":32 ,"price": 0}]
              }]}
     ],

如果我想访问数据" Y" - > " MC" - > " NUM"
如何从JsonObject访问它

 File file = new File(classLoader.getResource("files/BaggageInfoPolicy.json").getFile());

        Object obj = parser.parse(new FileReader(file));
        JSONObject jsonObject = (JSONObject) obj;

1 个答案:

答案 0 :(得分:0)

在JSON.org参考实现中,您可以这样做:

for (String key : JSONObject.getNames(jsonObject))
{
    map.put(key, jsonObject.get(key));
}

简单地说,您可以这样做:

for (Object keyObject : jsonObject.keySet())
{
    String key = (String)keyObject;
    map.put(key, (String)jsonObject.get(key));
}