【问题标题】:Read from .json file [duplicate]从.json文件中读取[重复]
【发布时间】:2016-08-10 08:51:49
【问题描述】:

您好,我无法在 Java 中读取包含以下结构的 .json 文件,

{"id":"1", "name":"A", "address":{"plot no":"22", "street":"road"}}
{"id":"2", "name":"A", "address":{"plot no":"22", "street":"road"}}
{"id":"3", "name":"A", "address":{"plot no":"22", "street":"road"}}
{"id":"4", "name":"A", "address":{"plot no":"22", "street":"road"}}

我有这样的 10k 条记录。我不能改变结构。我想阅读它并对“地址”进行处理。我需要一种有效的方法来读取它并仅获取地址。有什么建议吗?

【问题讨论】:

    标签: java json


    【解决方案1】:

    yourJsonObject 是您在 java 中作为 json 对象提取的 json 文件。还有这个:

    JSONObject jso = yourJsonObject.getJSONObject("address") ; 
    

    会将您的“地址”部分提取为 json 对象。然后就可以对它进行所有的经典处理了。

    【讨论】:

      【解决方案2】:

      你可以使用 JSON 简单的库,希望你能理解这个例子;

          JSONParser parser = new JSONParser();
          JSONArray a = (JSONArray) parser.parse(new FileReader("file name"));
      
          for (Object o : a){
            JSONObject person = (JSONObject) o;
      
            String name = (String) person.get("name");
            System.out.println(name);
      
            String city = (String) person.get("city");
            System.out.println(city);
      
            String job = (String) person.get("job");
            System.out.println(job);
      
           JSONArray cars = (JSONArray) jsonObject.get("cars");
      
           for (Object c : cars)
             {
              System.out.println(c+"");
              }
           }
      

      【讨论】:

        猜你喜欢
        • 2018-01-07
        • 1970-01-01
        • 1970-01-01
        • 2020-08-15
        • 1970-01-01
        • 2019-02-14
        • 2019-12-24
        • 1970-01-01
        • 2019-12-27
        相关资源
        最近更新 更多