读取具有多个属性的JSON文件

时间:2017-08-03 13:38:26

标签: java arrays json

我试图读取包含不同自行车阵列的JSON文件。当试图将自行车打印到java控制台时,我不断获得零点异常。我要做到这一点,以便所有的自行车都成为对象,但现在只是看看如何将它们打印出来。

 {
    "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"
            }
        ]
    }
}

JSON文件:

filledAreaWidth = viewModel.percentageFilled * cellWIdthCalculated
if filledAreaWidth != self.filledAreaView.frame.size.width {

        self.layoutIfNeeded()
        self.filledAreaView.snp.updateConstraints({ (make) in
            make.width.equalTo(self.filledAreaWidth)
        })

        UIView.animate(withDuration: 0.65, animations: {
            self.layoutIfNeeded()
        })
}

5 个答案:

答案 0 :(得分: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();
        } 
    }

答案 1 :(得分: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 :(得分:2)

您的对象为null,因为它不存在。为此,你需要有一个像这样的JSON文档的模式,

{
    "BikeList": [

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

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

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

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

// Find the list in the search object. 

其余代码就是您已有的代码。这会得到你的清单。

答案 3 :(得分: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

答案 4 :(得分:2)

使用Jackson 2创建java Pojos和注释

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]]]]