Why are you putting your list into Map? Code looks weird. If you want to return a list, just do it:
@RequestMapping("/getGodowns")
public @ResponseBody List<CscGodownBean> getGodownsBasedOnDistrict(@RequestParam(value="district_code") String dist_code) {
List<CscGodownBean> godown_list = null;
String exception = null;
try {
//getting name and codes here
godown_list = scm_service.getGodownListBesedOnDistCode(dist_code);
} catch (Exception ex) {
ex.printStackTrace();
exception = ex.getMessage();
}
return godown_list;
}
Answer from Leffchik on Stack OverflowWhy are you putting your list into Map? Code looks weird. If you want to return a list, just do it:
@RequestMapping("/getGodowns")
public @ResponseBody List<CscGodownBean> getGodownsBasedOnDistrict(@RequestParam(value="district_code") String dist_code) {
List<CscGodownBean> godown_list = null;
String exception = null;
try {
//getting name and codes here
godown_list = scm_service.getGodownListBesedOnDistCode(dist_code);
} catch (Exception ex) {
ex.printStackTrace();
exception = ex.getMessage();
}
return godown_list;
}
Change the return result from Map to List<CscGodownBean> and put : retrun godown_list
So;
@RequestMapping("/getGodowns")
public @ResponseBody List<CscGodownBean>
getGodownsBasedOnDistrict(@RequestParam(value="district_code") String
dist_code) {
List<CscGodownBean> godown_list = new ArrayList<CscGodownBean>();
String exception = null;
try
{
//getting name and codes here
godown_list = scm_service.getGodownListBesedOnDistCode(dist_code);
}catch(Exception ex)
{
ex.printStackTrace();
exception = ex.getMessage();
}
return godown_list ;
}
UPDATE
And you can return result as string and you will get what you need :
@RequestMapping("/getGodowns")
public @ResponseBody String
getGodownsBasedOnDistrict(@RequestParam(value="district_code") String
dist_code) {
List<CscGodownBean> godown_list = new ArrayList<CscGodownBean>();
String exception = null;
try
{
//getting name and codes here
godown_list = scm_service.getGodownListBesedOnDistCode(dist_code);
}catch(Exception ex)
{
ex.printStackTrace();
exception = ex.getMessage();
}
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
String arrayToJson = objectMapper.writeValueAsString(godown_list);
System.out.println("Convert List to JSON :");
System.out.println(arrayToJson);
return arrayToJson ;
}
The returned String is json format.
java - How to convert list of Objects to JSON in Spring MVC and Hibernate? - Stack Overflow
How to convert object to json in controller?
java - Convert a object into JSON in REST service by Spring MVC - Stack Overflow
java - How does Spring auto convert objects to json for @RestController - Stack Overflow
My project uses spring data embers for auditing and I would like users to be able to see the data in the auditing table using a controller endpoint. So something like โ/audit/2โ would give produce a JSON array with the auditing history of the model object that has an id of 2.
My repository class extends RevisionRepository and gives me some methods I can work with like findRevisions(id).
My question is how do I convert the output of this method (which is a Revision object) into a JSON array? Do I need a DTO to manually get its fields from the Revision object or is there an easier way?
Finally I got solution using Jackson library along with Spring MVC. I got this solution from an example of Journal Dev( http://www.journaldev.com/2552/spring-restful-web-service-example-with-json-jackson-and-client-program )
So, the code changes I have done are:
- Include the library in Maven.
- Add JSON conversion Servlet into servlet-context.xml.
- Change the Model into Serializable.
I didn't made any changes to my REST service controller. By default it converts into JSON.
You can always add the @Produces("application/json") above your web method or specify produces="application/json" to return json. Then on top of the Student class you can add @XmlRootElement from javax.xml.bind.annotation package.
Please note, it might not be a good idea to directly return model classes. Just a suggestion.
HTH.
You probably don't need custom deserializer to get this json. Just add @JsonFormat(shape = JsonFormat.Shape.OBJECT) annotation to your class:
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public static class PagedList<E> implements List<E> {
@JsonProperty
private List<E> list;
@JsonProperty // no need for this if you have getter-setters
private long totalRecords;
@JsonIgnore
@Override
public boolean isEmpty() {
return false;
}
...
Here is full demo: https://gist.github.com/varren/35c4ede769499b1290f98e39a2f85589
Update after comments:
I think Spring uses Jacksons return mapper.writerFor(List.class).writeValueAsString(new MyList()); Here is demo:
@RestController
@RequestMapping(value="/")
public static class MyRestController {
private static final ObjectMapper mapper = new ObjectMapper();
//returns [] for both 0 and 1
@RequestMapping(value="test", method = RequestMethod.GET)
public List test(@RequestParam int user) {
return user == 0 ? new ArrayList(): new MyList();
}
//returns [] for 0 and expected custom {"empty": true} for 1
@RequestMapping(value="testObj", method = RequestMethod.GET)
public Object testObj(@RequestParam int user) {
return user == 0 ? new ArrayList(): new MyList();
}
// returns expected custom {"empty": true}
@RequestMapping(value="testMyList", method = RequestMethod.GET)
public MyList testMyList() {
return new MyList();
}
// returns expected custom {"empty": true}
@RequestMapping(value="testMyListMapper", method = RequestMethod.GET)
public String testMyListMapper() throws JsonProcessingException {
return mapper.writeValueAsString(new MyList());
}
// returns []
@RequestMapping(value="testMyListMapperListWriter", method = RequestMethod.GET)
public String testMyListMapperListWriter() throws JsonProcessingException {
return mapper.writerFor(List.class).writeValueAsString(new MyList());
}
}
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public static class MyList extends ArrayList {}
So you have to Option 1) return Object instead of List or Option 2) register custom serialifer for List (and not for PageList) builder.serializerByType(List.class, new PagedListSerializer()); like this:
public class PagedListSerializer extends JsonSerializer<List> {
@Override
public void serialize(List valueObj, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
if (valueObj instanceof PagedList) {
PagedList value = (PagedList) valueObj;
gen.writeStartObject();
gen.writeNumberField("totalRecords", value.getTotalRecords());
gen.writeObjectField("list", value.getList());
gen.writeEndObject();
}else{
gen.writeStartArray();
for(Object obj : valueObj)
gen.writeObject(obj);
gen.writeEndArray();
}
}
}
You can Create your customObject Mapper and use your serializer there.
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="custom.CustomObjectMapper"/>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
Just return the list from the controller method
@RequestMapping(value = "/all", method = RequestMethod.GET)
@ResponseBody
public List<Object[]> getAllDeps() {
List<Object[]> list = departmentService.getAllDepartments();
return list;
}
The @ResponseBody annotation does the transformation for you.
public JSONObject findOccurrByFileUUID(UUID filePefin) throws JSONException {
StringBuilder strQuery = new StringBuilder();
strQuery.append("SELECT c.\"name\" AS creditorname, d.\"name\" AS debtorname, concat(b2.\"type\",'-',b2.\"number\",'-',b2.parcel) AS docto, b2.uniquenumber, to_char(b.dateoccurr,'DD/MM/YYYY HH24:MI:SS') AS dateoccur, to_char(b.createddate, 'DD/MM/YYYY HH24:MI:SS') AS createddate, b.statusnegatived, l.username FROM billnegativedoccurr b \n" +
"LEFT JOIN billnegatived b2 ON b2.uuid = b.billnegativeduuid \n" +
"LEFT JOIN creditor c ON c.tenantowner_uuid = b2.tenant_uuid AND c.uuid = b2.creditor_uuid \n" +
"LEFT JOIN debtor d ON d.tenantowner_uuid = b2.tenant_uuid AND d.uuid = b2.debtor_uuid \n" +
"INNER JOIN login l ON l.uuid = b.useroccurr \n" +
"WHERE b.filepefinuuid = :filePefin");
Query query = eM.createNativeQuery(strQuery.toString()); //no entity mapping
query.setParameter("filePefin", filePefin);
List<Object[]> queryList = query.getResultList();
JSONArray array = new JSONArray();
JSONObject obj = new JSONObject();
for (Object[] result : queryList) {
JSONObject object = new JSONObject();
object.put("creditorName", result[0]);
object.put("debtorName", result[1]);
object.put("docto", result[2]);
object.put("uniquenumber", result[3]);
object.put("dateoccur", result[4]);
object.put("createddate", result[5]);
object.put("statusnegatived", result[6]);
object.put("username", result[7]);
array.put(object);
}
return obj.put("Values", array);
}
Use GSON library for that. Here is the sample code
List<String> foo = new ArrayList<String>();
foo.add("A");
foo.add("B");
foo.add("C");
String json = new Gson().toJson(foo );
Here is the maven dependency for Gson
<dependencies>
<!-- Gson: Java to Json conversion -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.2</version>
<scope>compile</scope>
</dependency>
</dependencies>
Or you can directly download jar from here and put it in your class path
http://code.google.com/p/google-gson/downloads/detail?name=gson-1.0.jar&can=4&q=
To send Json to client you can use spring or in simple servlet add this code
response.getWriter().write(json);
You need an external library for this.
JSONArray jsonA = JSONArray.fromObject(mybeanList);
System.out.println(jsonA);
Google GSON is one of such libraries
You can also take a look here for examples on converting Java object collection to JSON string.