Android Spring@ResponseBody:格式化JSON以放置状态
我试图使用jackson技术使用spring创建web服务,将一些POJO映射为Android Spring@ResponseBody:格式化JSON以放置状态,android,json,spring,jackson,Android,Json,Spring,Jackson,我试图使用jackson技术使用spring创建web服务,将一些POJO映射为JSON,但我遇到了一个问题,当我将列表映射为JSON时,它会创建一个格式错误的JSON,如: ["idLine":"a61dcedb-4a6b-4f8f-bbdd-32cc51e861b2", "name":"line1", "code":"pru1" ] 我想创建一个映射器、一个过滤器或类似的东西,以获得如下响应: { status:"OK", data:[ {"idLine":
JSON
,但我遇到了一个问题,当我将列表映射为JSON
时,它会创建一个格式错误的JSON
,如:
["idLine":"a61dcedb-4a6b-4f8f-bbdd-32cc51e861b2",
"name":"line1",
"code":"pru1"
]
我想创建一个映射器
、一个过滤器
或类似的东西,以获得如下响应:
{
status:"OK",
data:[
{"idLine":"a61dcedb-4a6b-4f8f-bbdd-32cc51e861b2",
"name":"line1",
"code":"pru1"
}]
}
我用ObjectMapper
尝试了一些东西,但没有结果。
谢谢
更新
此行用于解析和调用格式错误的异常(它属于外部库)
我试图解析的JSON是:
[{"idLine":"a61dcedb-4a6b-4f8f-bbdd-32cc51e861b2","name":"linea1","code":"pru1","colour":"#ff3200","means":"Bus","type":"urban","notes":"","state":true,"timetableInterurbans":[]}]
为了澄清这一点,我在Spring上使用@ResponseBody序列化了一个Pojo,然后由android检索响应,并使用JSONObject进行解析,JSONObject会引发异常
服务器端方法:
@RequestMapping(value="/{country}/{cityName}/{type}", method=RequestMethod.GET)
public @ResponseBody List<Line> getUrbanLinesFromCity(@PathVariable String country, @PathVariable String cityName, @PathVariable String type){
//Get the city pojo by country and city name
City city = cityManager.searchCityByCountryAndName(country, cityName);
//Get the lines from the city
List<Line> lines = null;
if (city != null){
lines = lineManager.getLinesByCityAndType(city.getIdCity(), type);
}
return lines;
}
@RequestMapping(value=“/{country}/{cityName}/{type}”,method=RequestMethod.GET)
public@ResponseBody List getUrbanLinesFromCity(@PathVariable String country、@PathVariable String cityName、@PathVariable String type){
//按国家和城市名称获取城市pojo
City-City=cityManager.searchCityByCountryAndName(国家,城市名称);
//从城市里得到线索
列表行=空;
如果(城市!=null){
lines=lineManager.getLinesByCityAndType(city.getIdCity(),type);
}
回流线;
}
最后,我使用名为JSONResponse的助手类解决了这个问题。它有两个属性,一个表示请求的状态,另一个表示数据响应
public class JSONResponse{
private Object data;
private boolean status;
public JSONResponse (Object data){
this.data = data;
this.status = this.data != null;
}
//getters and setters for both attributes to be serialized
}
现在我唯一要做的就是用里面的数据序列化这个helper对象,使用@RequestBody JSONResponse
作为每个控制器中每个方法的返回值,通过多个API调用获得一致的JSON响应。您试图序列化的对象的结构是什么,它会产生格式错误的JSON?具体来说,列表的元素是什么?好的,我将修改我的帖子,以显示在JSONI解析时产生错误的条目。我已经更新了前面提到的代码。这个问题没有任何意义。您正在尝试序列化还是反序列化?另外,您提到了Jackson,但您的代码显示了JSON.org的用法。你可能想花点时间澄清你想做什么。好的,对不起。我将澄清这个问题,但首先:我在web服务上序列化它,并使用库在android设备上获取它。仅序列化
public class JSONResponse{
private Object data;
private boolean status;
public JSONResponse (Object data){
this.data = data;
this.status = this.data != null;
}
//getters and setters for both attributes to be serialized
}