Search code examples
javajsongsonpojo

Gson Parser unable to create objects from array


I am attempting to write a Gson parser to create POJO's from JMS messages. The messages are delivered in Text format in the following style:

{  
"priceUpdate":[  
  {  
     "symbol":"EUR/USD",
     "entryType":"0",
     "price":"1.09286"
  },
  {  
     "symbol":"EUR/USD",
     "entryType":"1",
     "price":"1.0929"
  }
 ]
}

I am trying to create Pojo objects for each item in the Array but the code fails when I attempt to parse:

public void consumeMessage(String text) {
    try {
        PriceUpdateTypeDTO updates = gson.fromJson(text,PriceUpdateTypeDTO.class);
        for (PriceUpdateItemDTO u : updates.items) {
            if (u.getEntryType() == "0") {
                connectedMarket.setBidPrice(Double.parseDouble(u.getPrice()));
            } else {
                connectedMarket.setOfferPrice(Double.parseDouble(u.getPrice()));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

I get a NullPointer when running on Tomcat Server

java.lang.NullPointerException
at com.markets.ticker.PriceStreamClient.consumeMessage(PriceStreamClient.java:25)

Here are my POJO classes:

public class PriceUpdateTypeDTO {


    private ArrayList<PriceUpdateItemDTO> items;
    //getter & setter
}


public class PriceUpdateItemDTO {

    private String symbol;

    private String entryType;

    private String price;
    //getters & setters
}

Solution

  • The name of your ArrayList in PriceUpdateTypeDTO needs to have the same name as the array in the JSON:

    Change

     private ArrayList<PriceUpdateItemDTO> items;
    

    to

     private ArrayList<PriceUpdateItemDTO> priceUpdate;
    

    or vice-versa (change the name of the array in the JSON to "items")