reset password
Author Message
hgadhia
Posts: 52
Posted 13:33 Feb 19, 2015 |

JSON object is the best way to handle AJAX responses. I have been working on PHP and there we can easily convert a given array to JSON object just by a simple function i.e. json_encode($arr); and this gives us the required JSON object.

I am new to using JSON in JAVA so I did some research on it and found out that there are no such simple solutions to it.

I found a project called Google GSON for doing this, but again requires a library to be imported, and again not very straight forward to setup.

My question is that, is there any easier way or in built feature in JAVA to convert JAVA object to JSON?

Any help will be appreciated.

armandop
Posts: 32
Posted 13:42 Feb 19, 2015 |

I tend to use org.json parser.  Give it a try.  I use it a lot with android (Java) development.

Armando Padilla

cysun
Posts: 2935
Posted 14:58 Feb 19, 2015 |

In Java there are many libraries that convert between Java objects and JSON. Jackson and Gson are probably the two most commonly used ones. Spring supports Jackson out of the box. Here are some examples of using JSON and Ajax in CSNS2:

. Return JSON Objects

1. Add jackson-databind dependency in pom.xml

2. Add a MappingJackson2JsonView view resolver in csns-servlet.xml.

3. Return the jsonView in controller. All model attributes will be converted automatically to JSON. See csns.web.service.NewsService for example. Search CSNS2 for "jsonView" for more examples.

. Return empty response

Often times you just need to return whether the operation is successful or not (like the check/uncheck operation in HW5). In other words instead of some object you just need to send back an empty response with the appropriate status code. For that you can use @ResponseStatus or @ResponseBody. See the csns.web.controller.CourseMappingControllerS for example:

  • removeCourse() always returns success.
  • addCourse() returns either success or failure.

 

 

Last edited by cysun at 22:38 Feb 19, 2015.
hgadhia
Posts: 52
Posted 19:22 Feb 19, 2015 |

Thank you Dr. Sun. It solved my question.