2017-08-03 3 views
1

Ich versuche eine JSON-Datei zu lesen, die eine Reihe verschiedener Fahrräder enthält. Beim Versuch, die Fahrräder an die Java-Konsole auszugeben, erhalte ich immer eine Nullpunkt-Ausnahme. Ich werde es so machen, dass alle Fahrräder in ein Objekt verwandelt werden, aber im Moment schaue nur, wie man sie ausdruckt.Eine JSON-Datei mit mehreren Attributen lesen

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-Datei:

{ 
    "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 ("Suchen") .get ("BikeList")? Sie müssen zuerst auf "Suche" zugreifen und dann 'BikeList' vom Objekt erhalten. – StanislavL

+0

warum nicht versuchen, Jackson Json Bibliothek zu verwenden? – Hector

Antwort

3

Zuerst müssen Sie das Objekt "Suchen" aufrufen. Und Sie können nicht nur das Objekt drucken. Sie müssen alle Attribute holen:

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

Danke. Das funktioniert :) – Elwin

2

, warum Sie nicht versuchen, diese.

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

Ihr Objekt ist null, weil es nicht existiert. Dafür brauchen Sie so ein Schema für JSON-Dokument haben,

{ 
    "BikeList": [ 

Der obige Code enthält, mit einer ersten Ebene BikeList. Was würdest du dann aus dem Code erfassen. Dies ist der Fehler in Ihrem Code. Ich glaube, Sie müssen zuerst die Search Knoten lesen, und dann auf den nächsten nach unten bewegen, um die Liste zu erfassen,

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

Auf diese Weise würden Sie zuerst das Search Objekt erhalten benötigen, dann bekommen die BikeList, Ansonsten wird es immer null sein.

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

// Find the list in the search object. 

Der Rest des Codes ist der, den Sie bereits haben. Dies würde die Liste für Sie bekommen.

2

statt

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

Sie haben die arrayBuilder wie diese

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

in einem Beispiel zu verwenden:

[ 
    { "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(); 

Quick-Info hier JsonArray

oder hier How to create correct JsonArray in Java using JSONObject

2

erstellen java Pojos und mit Anmerkungen versehen mit 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); 

    } 

} 

Ausgabe erhalten: -

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

Ich stimme dieser Lösung zu. Nur eine Anmerkung, die Annotation sind nicht obligatorisch, wenn die Eigenschaften in POJO und json –

+1

denselben Namen haben, erzeugte ich sie, also war es leichter, sie zu verlassen ... – Hector

Verwandte Themen