Gson 解析器无法从数组创建对象
Gson Parser unable to create objects from array
我正在尝试编写 Gson 解析器以从 JMS 消息创建 POJO。
消息以以下样式的文本格式传送:
{
"priceUpdate":[
{
"symbol":"EUR/USD",
"entryType":"0",
"price":"1.09286"
},
{
"symbol":"EUR/USD",
"entryType":"1",
"price":"1.0929"
}
]
}
我正在尝试为数组中的每个项目创建 Pojo 对象,但是当我尝试解析时代码失败:
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();
}
}
当 运行 在 Tomcat 服务器
上时,我得到一个 NullPointer
java.lang.NullPointerException
at com.markets.ticker.PriceStreamClient.consumeMessage(PriceStreamClient.java:25)
这是我的 POJO 类:
public class PriceUpdateTypeDTO {
private ArrayList<PriceUpdateItemDTO> items;
//getter & setter
}
public class PriceUpdateItemDTO {
private String symbol;
private String entryType;
private String price;
//getters & setters
}
PriceUpdateTypeDTO 中 ArrayList 的名称需要与 JSON:
中的数组同名
改变
private ArrayList<PriceUpdateItemDTO> items;
至
private ArrayList<PriceUpdateItemDTO> priceUpdate;
反之亦然(将JSON中的数组名称改为"items")
我正在尝试编写 Gson 解析器以从 JMS 消息创建 POJO。 消息以以下样式的文本格式传送:
{
"priceUpdate":[
{
"symbol":"EUR/USD",
"entryType":"0",
"price":"1.09286"
},
{
"symbol":"EUR/USD",
"entryType":"1",
"price":"1.0929"
}
]
}
我正在尝试为数组中的每个项目创建 Pojo 对象,但是当我尝试解析时代码失败:
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();
}
}
当 运行 在 Tomcat 服务器
上时,我得到一个 NullPointerjava.lang.NullPointerException
at com.markets.ticker.PriceStreamClient.consumeMessage(PriceStreamClient.java:25)
这是我的 POJO 类:
public class PriceUpdateTypeDTO {
private ArrayList<PriceUpdateItemDTO> items;
//getter & setter
}
public class PriceUpdateItemDTO {
private String symbol;
private String entryType;
private String price;
//getters & setters
}
PriceUpdateTypeDTO 中 ArrayList 的名称需要与 JSON:
中的数组同名改变
private ArrayList<PriceUpdateItemDTO> items;
至
private ArrayList<PriceUpdateItemDTO> priceUpdate;
反之亦然(将JSON中的数组名称改为"items")