1

I'm trying to read a JSON file that contains an array of different bikes. When trying to print out the bikes to the java console, i keep getting a null point exception. I'm going to make it so that all the bikes are made into object, but for now just looking on how to print them out.

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

 {
    "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"
            }
        ]
    }
}
Raju Sharma
  • 2,496
  • 3
  • 23
  • 41
Elwin
  • 71
  • 2
  • 9

5 Answers5

4

First you have to get the "Search" object. And also you can't just print the object. You need to fetch all the attributes:

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();
        } 
    }
JanTheGun
  • 2,165
  • 17
  • 25
2

Why Don't you try this.

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();
    }
Hiral
  • 119
  • 1
  • 8
2

Your object is null because, it does not exist. For that you need to have a schema for JSON document like this,

{
    "BikeList": [

The above code contains, a first-level BikeList. Which you would then capture from the code. This is the mistake in your code. I believe, you need to read the Search node first, and then move down to the next one to capture the list,

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

That way, you would first require to get the Search object, then get the BikeList, otherwise it will always be null.

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

// Find the list in the search object. 

Rest of code is the one you already have. This would get the list for you.

Afzaal Ahmad Zeeshan
  • 15,669
  • 12
  • 55
  • 103
2

instead of

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

you have to use the arrayBuilder like this

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

in an example:

 [
     { "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 here JsonArray

or here How to create correct JsonArray in Java using JSONObject

2

Create java Pojos and annotate with 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);

    }

}

output obtained:-

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]]]]
Hector
  • 4,016
  • 21
  • 112
  • 211
  • 1
    I agree with this solution. Just a note, the Annotation are not mandatory if the properties have same names in POJO and json – Andrea Girardi Aug 03 '17 at 14:03