【问题标题】:Reading a JSON file with multiple attributes读取具有多个属性的 JSON 文件
【发布时间】:2018-01-11 03:50:46
【问题描述】:

我正在尝试读取包含一系列不同自行车的 JSON 文件。尝试将自行车打印到 Java 控制台时,我不断收到空点异常。我打算把所有的自行车都做成物体,但现在只是看看如何打印出来。

public static void main(String[] args) {

    JSONParser parser = new JSONParser();

    try {
        Object obj = parser.parse(new FileReader("src/bikes.json"));

        JSONObject jsonObject = (JSONObject) obj;
        //System.out.println(jsonObject);

        JSONArray bikeList = (JSONArray) jsonObject.get("BikeList");

        Iterator<String> iterator = bikeList.iterator();
        while(iterator.hasNext()) {
            System.out.println(iterator.next());
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

JSON 文件:

 {
    "Search": {
        "BikeList": [
            {
                "weight": "14.8",
                "colour": "Blue",
                "price": 149.99,
                "name": "Hybrid Pro"
            },
            {
                "weight": "15.8",
                "colour": "Red",
                "price": 249.99,
                "name": "Slant comp"
            },
            {
                "weight": "17.9",
                "colour": "Pink",
                "price": 500.00,
                "name": "Charm"
            }
        ]
    }
}

【问题讨论】:

  • (JSONArray) jsonObject.get("Search").get("BikeList") ?需要先访问Search,再从对象中获取BikeList
  • 为什么不尝试使用 Jackson Json 库?

标签: java arrays json


【解决方案1】:

你为什么不试试这个。

public static void main(String[] args) {

    JSONParser parser = new JSONParser();

    try {
        Object obj = parser.parse(new FileReader("src/bikes.json"));

        JSONObject jsonObject = (JSONObject) obj;
        //System.out.println(jsonObject);

   *JSONArray Search= (JSONArray) jsonObject.get("Search");
   JSONArray bikeList = (JSONArray) Search.get("BikeList");*

        Iterator<String> iterator = bikeList.iterator();
        while(iterator.hasNext()) {
            System.out.println(iterator.next());
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

【讨论】:

    【解决方案2】:

    您的对象为空,因为它不存在。为此,您需要有这样的 JSON 文档架构,

    {
        "BikeList": [
    

    上面的代码包含一个一级BikeList。然后您将从代码中捕获。这是您的代码中的错误。我相信,你需要先阅读Search节点,然后向下移动到下一个捕获列表,

     {
        "Search": { // This one first.
            "BikeList": [
    

    这样,您首先需要获取Search 对象,然后获取BikeList,否则它将始终为空。

    // Search is an object, not an array.
    JSONObject search = (JSONObject) jsonObject.get("Search");
    
    // Find the list in the search object. 
    

    其余代码是您已经拥有的。这将为您获取列表。

    【讨论】:

      【解决方案3】:

      而不是

      JSONArray bikeList = (JSONArray) jsonObject.get("BikeList");
      

      你必须像这样使用arrayBuilder

       JsonArray array = Json.createArrayBuilder().build();
      

      举个例子:

       [
           { "type": "home", "number": "212 555-1234" },
           { "type": "fax", "number": "646 555-4567" }
       ]
      
      
      
       JsonArray value = Json.createArrayBuilder()
           .add(Json.createObjectBuilder()
               .add("type", "home")
               .add("number", "212 555-1234"))
           .add(Json.createObjectBuilder()
               .add("type", "fax")
               .add("number", "646 555-4567"))
           .build();
      

      快速信息在这里 JsonArray

      或这里 How to create correct JsonArray in Java using JSONObject

      【讨论】:

        【解决方案4】:

        首先你必须得到“搜索”对象。而且你不能只打印对象。您需要获取所有属性:

        public static void main(String[] args) {
        
                JSONParser parser = new JSONParser();
        
                try {
                    Object obj = parser.parse(new FileReader("src/bikes.json"));
        
                    JSONObject jsonObject = (JSONObject) obj;
                    // System.out.println(jsonObject);
        
                    JSONObject search = (JSONObject) jsonObject.get("Search");
                    JSONArray bikeList = (JSONArray) search.get("BikeList");
        
                    for (int i = 0; i < bikeList.size(); i++) {
                        JSONObject bike = (JSONObject) bikeList.get(i);
                        System.out.println("********************");
                        System.out.println("Weight: " + bike.get("weight"));
                        System.out.println("Colour: " + bike.get("colour"));
                        System.out.println("Price: " + bike.get("price"));
                        System.out.println("Name: " + bike.get("name"));
                    }
        
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (ParseException e) {
                    e.printStackTrace();
                } 
            }
        

        【讨论】:

          【解决方案5】:

          创建 java Pojos 并使用 Jackson 2 进行注释

          package com.example;
          
          import com.fasterxml.jackson.annotation.JsonInclude;
          import com.fasterxml.jackson.annotation.JsonProperty;
          import com.fasterxml.jackson.annotation.JsonPropertyOrder;
          
          @JsonInclude(JsonInclude.Include.NON_NULL)
          @JsonPropertyOrder({ "Search" })
          public class Bike {
          
              @JsonProperty("Search")
              private Search search;
          
              /**
               * No args constructor for use in serialization
               * 
               */
              public Bike() {
              }
          
              /**
               * 
               * @param search
               */
              public Bike(final Search search) {
                  super();
                  this.search = search;
              }
          
              @JsonProperty("Search")
              public Search getSearch() {
                  return search;
              }
          
              @JsonProperty("Search")
              public void setSearch(final Search search) {
                  this.search = search;
              }
          
              @Override
              public String toString() {
                  return "Bike [search=" + search + "]";
              }
          
          }
          
          
          
          package com.example;
          
          import java.util.List;
          
          import com.fasterxml.jackson.annotation.JsonInclude;
          import com.fasterxml.jackson.annotation.JsonProperty;
          import com.fasterxml.jackson.annotation.JsonPropertyOrder;
          
          @JsonInclude(JsonInclude.Include.NON_NULL)
          @JsonPropertyOrder({ "BikeList" })
          public class Search {
          
              @JsonProperty("BikeList")
              private List<BikeList> bikeList = null;
          
              /**
               * No args constructor for use in serialization
               * 
               */
              public Search() {
              }
          
              /**
               * 
               * @param bikeList
               */
              public Search(final List<BikeList> bikeList) {
                  super();
                  this.bikeList = bikeList;
              }
          
              @JsonProperty("BikeList")
              public List<BikeList> getBikeList() {
                  return bikeList;
              }
          
              @JsonProperty("BikeList")
              public void setBikeList(final List<BikeList> bikeList) {
                  this.bikeList = bikeList;
              }
          
              @Override
              public String toString() {
                  return "Search [bikeList=" + bikeList + "]";
              }
          
          }
          
          
          
          
          
          package com.example;
          
          import com.fasterxml.jackson.annotation.JsonInclude;
          import com.fasterxml.jackson.annotation.JsonProperty;
          import com.fasterxml.jackson.annotation.JsonPropertyOrder;
          
          @JsonInclude(JsonInclude.Include.NON_NULL)
          @JsonPropertyOrder({ "weight", "colour", "price", "name" })
          public class BikeList {
          
              @JsonProperty("weight")
              private String weight;
              @JsonProperty("colour")
              private String colour;
              @JsonProperty("price")
              private Double price;
              @JsonProperty("name")
              private String name;
          
              /**
               * No args constructor for use in serialization
               * 
               */
              public BikeList() {
              }
          
              /**
               * 
               * @param colour
               * @param price
               * @param weight
               * @param name
               */
              public BikeList(final String weight, final String colour, final Double price, final String name) {
                  super();
                  this.weight = weight;
                  this.colour = colour;
                  this.price = price;
                  this.name = name;
              }
          
              @JsonProperty("weight")
              public String getWeight() {
                  return weight;
              }
          
              @JsonProperty("weight")
              public void setWeight(final String weight) {
                  this.weight = weight;
              }
          
              @JsonProperty("colour")
              public String getColour() {
                  return colour;
              }
          
              @JsonProperty("colour")
              public void setColour(final String colour) {
                  this.colour = colour;
              }
          
              @JsonProperty("price")
              public Double getPrice() {
                  return price;
              }
          
              @JsonProperty("price")
              public void setPrice(final Double price) {
                  this.price = price;
              }
          
              @JsonProperty("name")
              public String getName() {
                  return name;
              }
          
              @JsonProperty("name")
              public void setName(final String name) {
                  this.name = name;
              }
          
              @Override
              public String toString() {
                  return "BikeList [weight=" + weight + ", colour=" + colour + ", price=" + price + ", name=" + name + "]";
              }
          
          }
          
          
          Then employ Jackson to read input json and convert to Java Objects
          
          package com.example;
          
          import java.io.File;
          import java.io.IOException;
          
          import com.fasterxml.jackson.databind.ObjectMapper;
          import com.fasterxml.jackson.databind.ObjectReader;
          
          public class Stackoverflow {
          
              private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
              private static final ObjectReader OBJECT_READER_BIKE = OBJECT_MAPPER.readerFor(Bike.class);
          
              public static void main(final String[] args) throws IOException {
          
                  final Bike bike = OBJECT_READER_BIKE.readValue(new File("input/bike.json"));
          
                  System.out.println(bike);
          
              }
          
          }
          

          获得的输出:-

          Bike [search=Search [bikeList=[BikeList [weight=14.8, colour=Blue, price=149.99, name=Hybrid Pro], BikeList [weight=15.8, colour=Red, price=249.99, name=Slant comp], BikeList [weight=17.9, colour=Pink, price=500.0, name=Charm]]]]
          

          【讨论】:

          • 我同意这个解决方案。请注意,如果属性在 POJO 和 json 中具有相同的名称,则注解不是强制性的
          猜你喜欢
          • 2019-05-14
          • 2020-05-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-05-31
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多