java 如何将json字符串转换为java对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11896945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert json String to java object
提问by subbusaabu
From jsp through ajax cal I'm passing json string to server and I am converting to json object. How can I convert the jsonobject to a model class object in java?
从jsp到ajax cal我将json字符串传递给服务器,我正在转换为json对象。如何在java中将jsonobject转换为模型类对象?
In server I'm doing this:
在服务器中我这样做:
HttpServletRequest request = ServletActionContext.getRequest();
String jsonData = request.getParameter("JsonData");
JSONObject jsonDataObject = (JSONObject) JSONSerializer.toJSON( jsonData );
My model classes looks like this:
我的模型类如下所示:
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
}
and I am getting jsonData String as
我得到 jsonData String 作为
{"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"}]}]}
How can I convert JSONObject jsonDataObject ( or String jsonData) to model class object(ie vehicles) in java?
如何在java中将JSONObject jsonDataObject(或String jsonData)转换为模型类对象(即车辆)?
回答by Brittas
use this..
用这个..
import org.codehaus.Hymanson.map.ObjectMapper;
import org.json.JSONException;
import org.json.JSONObject;
HttpServletRequest request = ServletActionContext.getRequest();
Vehicles vehicles;
String jsonData = request.getParameter("JsonData");
jsonData = jsonData.substring(13, jsonData.length()-2);
ObjectMapper mapper = new ObjectMapper();
try{
vehicles= mapper.readValue(jsonData, Vehicles.class);
}
catch (Exception e) {
e.printStackTrace();
}