【问题标题】:How to serialize list of objects using GSON如何使用 GSON 序列化对象列表
【发布时间】:2014-07-15 10:20:15
【问题描述】:

我正在使用 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 响应。请指导我。

【问题讨论】:

    标签: java json spring gson


    【解决方案1】:

    您需要在示例数据中添加属性值,否则您将得到空白数据[{}]。

    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);
    

    【讨论】:

    • 我有一个样本对象,其中有 category 另一个对象,那么如何使用 gson 在 sample 对象中设置 category 对象
    • 您可以在 Sample 类中创建一个属性来设置类别对象 - 修改上面的代码。
    • 是的,它已经完成了,但是我在问题中已经提到过堆栈溢出错误
    • 您的list.add(new SampleData()); 这一行返回空白数据。
    猜你喜欢
    • 1970-01-01
    • 2013-07-18
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-25
    相关资源
    最近更新 更多