2017-08-03 55 views
1

我正在尝试阅读包含不同自行车数组的JSON文件。当试图将自行车打印到java控制台时,我不断收到零点异常。我打算让所有的自行车都成为对象,但现在只是看看如何打印出来。阅读具有多个属性的JSON文件

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" 
      } 
     ] 
    } 
} 
+2

(JSONArray),其中jsonObject.get( “搜索” ).get(“BikeList”)?您需要首先访问'Search',然后从对象中获取'BikeList'。 – StanislavL

+0

为什么不尝试使用Jackson Json库? – Hector

回答

3

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

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(); 
     } 
    } 
+0

谢谢。这工作:) – Elwin

2

你为什么不试试这个。

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. 

其余的代码是你已经拥有的代码。这会得到你的名单。

2

代替

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

2

创建Java POJO和杰克逊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]]]] 
+1

我同意这个解决方案。请注意,如果属性在POJO和json中具有相同的名称,那么Annotation不是必需的 –

+1

我生成了它们,因此更容易让它们变为... – Hector