2017-08-03 52 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