将json字符串转换为java中的pojo类对象 [英] convert json string to pojo class object in java
问题描述
我创建了JSON字符串,就像
I have created JSON string as like ths
{"vehicles":[{"vehicle":[{"department":[{"Item":[{"itemId":31,"itemName":"c7"},{"itemId":32,"itemName":"c2"}],"depId":21,"departmentName":"d1"}],"vId":11,"VName":"aaa"},{"department":[{"Item":[{"itemId":33,"itemName":"c3"},{"itemId":34,"itemName":"c4"}],"depId":22,"departmentName":"d2"},{"Item":[{"itemId":36,"itemName":"c1"}],"depId":24,"departmentName":"d3"}],"vId":12,"VName":"bbbb"},{"department":[{"Item":[{"itemId":30,"itemName":"c6"},{"itemId":35,"itemName":"c5"}],"depId":23,"departmentName":"d4"}],"vId":13,"VName":"cccc"},{"department":[{"Item":[{"itemid":37,"itemName":"c8","status":0}],"depId":25,"departmentName":"d5"}],"vId":14,"VName":"ddd"}]}]}
我尝试使用以下代码转换相同内容
I tried to convert the same with the below code
Gson gsonObj = new Gson();
Vehicles vehicles = gsonObj.fromJson(jsonData, Vehicles.class);
但车辆变量显示空值。如何将json字符串转换为pojo类对象?
我的pojo类如下:
but vehicles variable is showing a null value. How can I convert a json string to a pojo class object?
my pojo class are as the following
public class Vehicles {
private List<Vehicle> vehicle;
public List<Vehicle> getVehicle() {
return vehicle;
}
public void setVehicle(List<Vehicle> vehicle) {
this.vehicle= vehicle;
}
}
和
and
public class Vehicle{
private Integer vId;
private String VName;
private List<Department> department;
//getters and setters;
}
和
and
public class Department{
private Integer depId;
private String departmentName;
private List<Item> item;
//getters and setters
}
和
and
public class Item{
private Integer itemId;
private String itemName;
//getters and setters
}
推荐答案
你将错误的json值传递给Gson Parser。
你的Json字符串从
You are passing wrong value of json to the Gson Parser.
Your Json String starting from the
{vehicles:[{vehicle:[{department:[...
{"vehicles":[{"vehicle":[{"department":[...
所以对象的第一个元素是车辆和
so the first element of the object is vehicles and in the
Vehicles.class
Vehicles.class
没有名为vehicle的变量,因此它无法分配值。
您只需要更新字符串以从数组开始
there is no variable named vehicles so it can not assinging values.
You just need to update string to start from array
{vehicle:[{department :[{Item:字符串上方的{{...
{"vehicle":[{"department":[{"Item":[{...
将成功运行并解析为对象。
above string will successfully run and parse into object.
请让我们从本教程中获得完整的项目。
BR
Mehdi
Hi,
please let us to have complete project from this Tutorial.
BR
Mehdi
>
这篇关于将json字符串转换为java中的pojo类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!