简体   繁体   中英

How to serialize list of objects using GSON

I am using GSON library to send JSON response. I have a model which has a couple fields. Now my code is for sending JSON response is:

@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
}

I don't know how to return JSON response of sample data objects fields. Please guide me.

You need to add property values in the sample data, otherwise you will get blank data [{}] as you are getting.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM