我正在使用GSON库发送JSON响应。我有一个有几个领域的模型。现在我的代码用于发送JSON响应:
@RequestMapping(value="/sampleData/info", headers="Accept=*/*", method=RequestMethod.GET)
public @ResponseBody String getDealerInfoInJSON(@RequestParam("city") String city_id,
@RequestParam("dealer") String category_id) {
Gson gson = new Gson();
String s;
List<SampleData> foo = sampleDataService.getDealerInfo(city_id, category_id);
// foo contains [com.spring.model.SampleData@e64a0b]
List<SampleData> list = Collections.synchronizedList(
new Arraylist<SampleData>());
Iterator<SampleData> iterator = foo.iterator();
while (iterator.hasNext()) {
// Here I want to add sample data obj in list which is not working but
// new SampleData is working fine like added below:
list.add(iterator.next()) // Not working (stack overflow error)
list.add(new SampleData()); // Working
}
s = gson.toJson(list, ArrayList.class);
System.out.println(s); // This print [{}]
return s; // Works fine with a single object but not a list of objects
}
我不知道如何返回示例数据对象字段的JSON响应。请指导我。
答案 0 :(得分:0)
您需要在示例数据中添加属性值,否则您将获得空白数据[{}]。
SampleData sample= new SampleData();
sample.setXXX(); // your setter methods to set data in object.
sample.setYYY();
sample.setCategory(category);
Gson gson = new Gson();
return gson.toJson(sample);