2013-05-14 40 views
0

我试图用jackson技术将一些pojos映射为使用spring创建web服务的技术,但我遇到了问题,当我将一个列表映射为JSON时,它创建了一个格式不正确的JSON像:Spring @ResponseBody:将JSON格式化为状态

["idLine":"a61dcedb-4a6b-4f8f-bbdd-32cc51e861b2", 
    "name":"line1", 
    "code":"pru1" 
] 

我想创建一个mapper,一个filter或类似的得到这样的回应了一句:

{ 
status:"OK", 
data:[ 
    {"idLine":"a61dcedb-4a6b-4f8f-bbdd-32cc51e861b2", 
    "name":"line1", 
    "code":"pru1" 
    }] 
} 

我已经tryed一些与ObjectMapper,但没有结果。 谢谢。

UPDATE 此行是一个分析和调用异常例外的一个(它属于一种外部库)

result = (JSONObject) new JSONTokener(str).nextValue(); 

而且,我试图解析JSON是:

[{"idLine":"a61dcedb-4a6b-4f8f-bbdd-32cc51e861b2","name":"linea1","code":"pru1","colour":"#ff3200","means":"Bus","type":"urban","notes":"","state":true,"timetableInterurbans":[]}] 

为了澄清,我使用@ResponseBody序列化Spring上的Pojo,然后通过android检索响应,并使用引发异常的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; 
} 
+0

你试图序列化的对象的结构是什么,会产生格式不正确的json?具体来说,列表的元素是什么? –

+0

好的,我会修改我的帖子,以显示JSON解析时产生错误的条目 – droidpl

+0

我已经更新了代码 – droidpl

回答

0

最后我通过使用叫做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 
} 

现在我要做的唯一事情是序列化此辅助对象,与里面的数据,在获得使用@RequestBody JSONResponse为每个控制器的每个方法的返回值的多个API调用一致的JSON响应。