2014-07-15 3 views
0

GSON 라이브러리를 사용하여 JSON 응답을 보내고 있습니다. 몇 가지 필드가있는 모델이 있습니다. 이제 내 코드 JSON 응답을 보내는 것입니다 :GSON을 사용하여 객체 목록을 직렬화하는 방법

@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 [[email protected]] 

    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

샘플 데이터에 속성 값을 추가해야합니다. 그렇지 않으면 빈 데이터 [{}]가 표시됩니다.

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

나는'나는 당신이 카테고리 객체를 설정하는 샘플 클래스에서 하나 개의 속성을 만들 수 있습니다 GSON –

+0

를 사용하여'sample' 대상'에서 category' 객체를 설정하는 방법 그래서 다른 객체를 category' 한 샘플 개체가 - 수정 된 코드를 위. –

+0

예 이미 완료되었지만 스택 오버 플로우 오류가 있습니다. 내 질문에 이미 언급했기 때문입니다. –

관련 문제