0

我正在尝试映射一些 pojo,就像JSON使用 spring 的杰克逊技术创建 Web 服务一样,但是当我映射一个列表时,我遇到了一个问题,因为JSON它创建了一个格式错误JSON,例如:

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

我想创建 a mapper、 afilter或类似的东西以获得如下响应:

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

我尝试了一些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":[]}]

为了澄清,我在 Spring 上使用 @ResponseBody 序列化 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;
}
4

1 回答 1

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
}

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

于 2013-05-16T18:22:10.640 回答