Spring MVC Controller with JSON and JSP - spring

Can the same method in a controller be used for both JSP and other MIME types (like XML and JSON)?
I know of the following ways to resolve views in Spring MVC.
Return a String with the view name and add attributes to the Model or ModelMap
Return a ModelAndView with the view name and model
Return an Object with a #ResponseBody annotation
I use 1 or 2 when I am dealing with JSP and 3 when I want to return JSON or XML.
I know I can use two methods and with the #RequestMapping(headers="accept=application/xml") or #produces annotations to define which MIME types they handle, but is it possible to do this in just one method?
The controller logic is pretty simple and it seems like unnecessary duplication to have two different methods mapped which return the same exact model, or is this just simply the way it's done?

Yes, this is straight forward in Spring MVC 3.x...
You basically write your controller methods for just normal JSP page views and then you configure a ContentNegotiatingViewResolver bean in your Dispatcher servlet config., which looks at the requested mime-type (or file extension) and returns the appropriate output type.
Follow the instructions here: Spring 3 MVC ContentNegotiatingViewResolver Example

I had the very same requirement recently, and below is my code. validateTicket returns jsp name and sendForgotPassword mail returns json. My spring version is 4.0.0.RELEASE. Of course, if I need to return complex json then I'd definitely register Jackson converter - http://docs.spring.io/spring/docs/4.0.x/javadoc-api/org/springframework/http/converter/json/MappingJackson2HttpMessageConverter.html
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="foo.bar" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
#Controller
#RequestMapping("/forgot-password")
public class ForgotPasswordController {
#RequestMapping(value="/reset-password", method = RequestMethod.GET)
public String validateTicket(#RequestParam String ticket, #RequestParam String emailAddress) {
return "resetPassword";
}
#RequestMapping(value="/send-mail", method = RequestMethod.POST, produces="application/json")
public #ResponseBody String sendForgotPasswordMail(#RequestParam String emailAddress) throws LoginException {
return "{\"success\":\"true\"}";
}
}

Related

Having to use deprecated classes with Spring MVC

Have been trial Spring Web MVC (4.2.5) and have his a number of issues trying to use a DispatcherServlet and
<mvc:annotation-driven />
Have setup a simple #Controller class and wanted to use the POJO to JSON mapping. The docu said that if Jackson was detected on the class path it would be used automatically, however this didn't work for me and I was forced to use the 'deprecated' AnnotationMethodHandlerAdapter
<bean name="mappingJackson2HttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >
<property name="messageConverters" ref="mappingJackson2HttpMessageConverter"/>
</bean>
which then worked fine.
Equally, tried to create a #ControllerAdvice class for handling all exceptions, but only got an #ExceptionHandler method working on the same controller class, and that was only when I added the (again) deprecated AnnotationMethodHandlerExceptionResolver to the context.
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver" />
Having to instantiate two deprecated classes suggests I am doing something wrong, especially when all the tutorials seem to suggest this should all 'just work', but I cannot see what (and indeed nosing through the Spring source I cannot see how the default and recommended handlers would work anyway)
There are no errors, the annotation simply aren't detected. The fill context xml is
please find the entire context XML below (is very simple)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven enable-matrix-variables="true"/>
<bean name="mappingJackson2HttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >
<property name="messageConverters" ref="mappingJackson2HttpMessageConverter"/>
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver" />
<context:component-scan base-package="com.domain.datastore.dao"/>
<context:component-scan base-package="com.domain.service"/>
<context:component-scan base-package="com.domain.uiapi"/>
</beans>
An example controller is
#RestController("/place/*")
public class PlaceController {
private PlaceService placeService;
#Autowired
public PlaceController(PlaceService placeService) {
this.placeService = placeService;
}
#RequestMapping(path="/{id}", method = RequestMethod.GET)
public #ResponseBody Place getPlace(#PathVariable("id") long id, Model model) {
return placeService.getPlace(id);
}
}
and the cross-cutting exception handler is
#ControllerAdvice
public class GlobalExceptionController {
public GlobalExceptionController() {
System.out.println("GlobalExceptionController");
}
#ResponseStatus(HttpStatus.NOT_FOUND)
#ExceptionHandler(NotFoundException.class)
public ModelAndView handleCustomException(NotFoundException ex) {
return null;
}
}
The issue was that Spring MVC was matching the path in
#RestController("/place/*")
And as such passing the instance of PlaceController around as the handler. The ExceptionHandlerExceptionResolver expects a HandlerMethod and so was unable to process the exception.
As such dropping the path from the class annotation and putting the full path in the method got it all working and I dropped all the deprecated beans.
#RestController
public class PlaceController {
#RequestMapping(path="/place/{id}", method = RequestMethod.GET)
public #ResponseBody Place getPlace(#PathVariable("id") long id, Model model)
What I am not sure is if this is a bug. Shouldn't it be possible to put the 'base' path in the RestController annotation and the subpath in the RequestMapping?
As far as I can understand you don't want to use a deprecated class. AnnotationMethodHandlerAdapter is indeed Deprecated. As doc suggest you should use RequestMappingHandlerAdapter instead.
See here for the details.
And instead of AnnotationMethodHandlerExceptionResolver you can use ExceptionHandlerExceptionResolver.

Spring MVC validation ignored

I have Spring MVC app on Tomcat. I'm trying to add validation in it.
For some reason my validation is ignored and not checked.
Here is my POJO
import org.hibernate.validator.constraints.Range;
public class Goal {
#Range(min = 1, max = 15)
private int minutes;
public int getMinutes() {
return minutes;
}
public void setMinutes(int minutes) {
this.minutes = minutes;
}
}
And controller
import org.springframework.validation.BindingResult;
import javax.validation.Valid;
#Controller
#SessionAttributes("goal")
public class GoalController {
#RequestMapping(value = "addGoal", method = RequestMethod.POST)
public String updGoal(#ModelAttribute("goal") #Valid Goal goal, BindingResult result) {
System.out.println(goal.getMinutes());
System.out.println(result.hasErrors());
if(result.hasErrors()) {
return "addGoal";
}
return "redirect:addMinutes.html";
}
}
But even if I try to put any negative values as "minutes" there no errors produced.
Added configuration
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="com.xlab.ice.mvc.controller"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
<mvc:resources mapping="/pdfs/**" location="pdf"/>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource" p:basename="messages"/>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" p:defaultLocale="en"/>
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" p:paramName="lang"/>
</mvc:interceptors>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" p:order="0"/>
</beans>
Can you please also confirm that you have a JSR 303 implementation in your classpath - say hibernate-validator jar files.
You need <mvc:annotation-driven /> to enable jsr-303 validation, This is needed for the #Valid annotation to actually do anything.
try adding <mvc:annotation-driven/> in servlet context XML if not done.
schemaLocation the mvc entry should contain these two:
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
Solution is simple.
Validation libraries must be placed into classpath.
DISCLAIMER : In the absence of complete relevant controller code and the suspicion that Validator library might be missing in classpath, here is a small test to just check the configuration. You can use this very quickly to find if all configurations are in place with just removing the session attribute part.
Let's give it a try. To simplify testing with a REST Client and also incomplete code I have not used SessionAttributes. Also there is Hibernate validator library on my runtime classpath. Also I have used ResponseBody annotation to let the Spring automatically convert the String to response text without making use of alternate view technology (like jsp).
import org.hibernate.validator.constraints.Range;
public class Goal {
#Range(min = 1, max = 15)
private int minutes;
public int getMinutes() {
return minutes;
}
public void setMinutes(int minutes) {
this.minutes = minutes;
}
}
Then my controller
#Controller
public class GoalController {
#RequestMapping(value = "/addGoal", method = RequestMethod.POST)
public #ResponseBody String updGoal(#ModelAttribute("goal") #Valid Goal goal, BindingResult result) {
System.out.println(goal.getMinutes());
System.out.println(result.hasErrors());
if(result.hasErrors()) {
return "Errors !";
}
return "No Errors !";
}
}
Hitting the application with a rest client on http://localhost:8080/testApp/addGoal with POST parameters as minutes=1 gives me response as No Errors ! while with minutes=-1 gives me Errors !

Spring controller not accepting application/json

When I am passing application/json parameters from Chrome Rest Client,I am getting 400 bad request error.
When I add required=false for #RequestParam, the request is accepted by Controller but the values is Null.
#RequestMapping(value = "/add",
method = RequestMethod.POST,
consumes="application/json",
produces="application/json")
public #ResponseBody String add(
#RequestParam(value="surveyName") String surveyName,
#RequestParam(value="surveyDesc") String surveyDesc,
ModelMap model) throws Exception
{
System.out.println("request parameters in /add/syrvey surveyName= "+surveyName);
}
My JSON request is as below and Content-Type is "aplication/json"
{"surveyName"="sd", "surveyDesc":"sd"}
I tried using headers="Accept=application/json",but it didn't help much.
My dispatcher-servlet is
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=">
<context:annotation-config />
<context:component-scan base-package="com.survey.controller" />
<context:component-scan base-package="com.survey.service" />
<context:component-scan base-package="com.survey.dao" />
<context:component-scan base-package="com.survey.entity" />
<context:component-scan base-package="com.survey.constants" />
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jacksonMessageConverter" />
</list>
</property>
</bean>
</beans>
My pom.xml is
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.12</version>
</dependency>
Any help greatly appreciated
In your situation you can use a Map:
public #ResponseBody String add(#RequestBody Map<String, String> input) throws Exception
and then iterate over it in order to find your parameters, or you can use a Pojo
public class Pojo {
private String surveyName;
private String surveyDesc;
...
}
public #ResponseBody String add(#RequestBody Pojo pojo) throws Exception
Hope this can be useful!
#RequestParam can not be used to load parts of a complex json object. It is designed for selecting request parameter, but not to select something within a (single) request parameter.
You need to use #RequestBody and a container object
public class MyContainer {
private String surveyName;
private String surveyDesc;
...
}
public #ResponseBody String add(#RequestBody Container container){...}
Or you can implement a solution described by Biju Kunjummen in his answer to a similar question. The idea is to implement your own HandlerMethodArgumentResolver that is triggered by an parameter annotation which take a JsonPath expression argument
public #ResponseBody String add(
#JsonArg("/surveyName") String surveyName,
#JsonArg("/surveyDesc") String surveyDesc){...}
Have a look at Passing multiple variables in #RequestBody to a Spring MVC controller using Ajax for the implementation details.
If you like this answer, then please also upvote Biju Kunjummen answer, because it is his idea. I only goggled a bit because it is an interesting question.
also add those two library in lib or add maven for this.
jackson-jaxrs-1.6.1.jar
jackson-mapper-asl-1.9.9.jar

Can I combine #controller and XML bean mapping in spring?

I currently have a #Controller declared in spring and have a bunch of mappings done like so:
#RequestMapping(value = "foo", method = RequestMethod.GET)
public ModelAndView foo() {
ModelAndView mav = new ModelAndView(
"myjsp");
return mav;
}
However every time I want to add a simple JSP mapping I need to recompile and build a new war and deploy.
This isnt so bad except sometimes other members of the team have requests and it would be easier if they can just go into the test env and create the mapping themselves without having to recompile.
I know that you can do similar mapping using xml but can I do this at the same time that I have the #Controller defined?
Like in the example above how could I define that mapping in XML rather than in java?
or say I needed foo2 to map to myjsp2.jsp
I am using spring MVC 3.2
Look into BeanNameUrlHandlerMapping which allows you specify url patterns for controllers in your configuration. Documentation
Example
<beans>
<bean id="handlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<bean name="/editaccount.form" class="org.springframework.web.servlet.mvc.SimpleFormController">
<property name="formView" value="account"/>
<property name="successView" value="account-created"/>
<property name="commandName" value="account"/>
<property name="commandClass" value="samples.Account"/>
</bean>
<beans>

Spring JSON causes problems when the Spring framework is upgraded from 3.0.2 to 3.2.0

I was working with a web application using the Spring framework version 3.0.2 along with Hibernate (NetBeans 6.9.1). Later I came to know that there was one of bugs that was causing problems in uploading multiple files as mentioned in my one of previous questions.
I have finished struggling to acquire the solution but couldn't succeed. Therefore, I upgraded the Spring version to 3.2.0.
With the earlier version (3.0.2), AJAX was working fine with Jackson 1.9.8 (its download page) but with the later version (3.2.0), everything works fine but AJAX calls alert an error everywhere in the JavaScript code.
There is a scenario at one place when one of the countries is selected in the country select box, the corresponding state list is retrieved from the Spring controller along with DAO. The method which is mapped with a URL in the Spring controller is as follows,
#RequestMapping(value="ajax/GetStateList", method=RequestMethod.GET)
public #ResponseBody List<Object[]> getStateSelectBox(HttpServletRequest request)
{
return cityService.getStateSelectBox(request.getParameter("countryId"));
}
This method is invoked when a country is selected in the country select box. The getStateSelectBox() method is defined in one of DAO classes as follows,
#Service
#Transactional(readOnly = true, propagation=Propagation.REQUIRES_NEW)
public final class CityDAO implements CityService
{
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory)
{
this.sessionFactory = sessionFactory;
}
#SuppressWarnings("unchecked")
public List<Object[]> getStateSelectBox(String id)
{
List<Object[]> list = sessionFactory.getCurrentSession()
.createQuery("select s.stateId, s.stateName from StateTable s where countryId.countryId=:id order by s.stateId")
.setParameter("id", Long.parseLong(id)).list();
for(Object[]o:list)
{
System.out.println(o[0]+" : "+o[1]);
}
return list;
}
}
The foreach loop is just for the sake of demonstration, it displays all the states along with their id that correspond to the countryId supplied by the AJAX request but the List is not returned to JSP.
The JavaScript code used to send this AJAX request alerts an error. It appears that there are some problems with JSON mapping. The same thing was working with the earlier version of the Spring framework (3.0.2). I'm not sure why does this cause problems with the higher version of Spring which is 3.2.0. Is there anything with the Spring version 3.2.0 which I might be missing?
If you needed to see the JavaScript code, the full JavaScript code to achieve this would be as follows.
function getStates(countryId)
{
if(countryId==""||countryId==null||countryId==undefined||isNaN(countryId))
{
var str="<select id='cmbStates' name='cmbStates' onchange='errorMessage(this.value);' class='validate[required] text-input'><option value=''>Select</option></select>";
$('#stateList').html(str);
alert("Please select an appropriate option.");
return;
}
var div=document.createElement("div");
div.id="temp";
document.body.appendChild(div);
$.ajax({
datatype:"json",
type: "GET",
contentType: "application/json",
url: "/wagafashion/ajax/GetStateList.htm",
data: "countryId=" + countryId+"&t="+new Date().getTime(),
success: function(response)
{
if(typeof response==='object'&&response instanceof Array)
{
var str="<select id='cmbState' name='cmbState' onchange='errorMessage(this.value);' class='validate[required] text-input'><option value=''>Select</option>";
var l=response.length;
for(var i=0;i<l;i++)
{
str+="<option value='"+response[i][0]+"'>"+$('#temp').text(response[i][1]).html()+"</option>";
}
str+="</select>";
$('#stateList').html(str); // select box is written to #stateList div
$('#temp').remove();
}
},
error: function(e)
{
alert('Error: ' + e);
}
});
}
To be sure, the Jackson library is on the classpath and I'm not getting any error or exception on the server side. The AJAX request succeeds and it goes to the DAO via Spring and the list of type List<Object[]> is retrieved from the database but it is not a response of JSON to JSP (which could/should be mapped to a JavaScript array). presumably, it appears that there is something missing with JSON mapping which was however not the case with the earlier version of Spring.
EDIT:
I have tried to parse List<Object[]> in both of the frameworks, 3.0.2 and 3.2.0 such as
List<Object[]> list = cityService.getStateSelectBox(request.getParameter("countryId"));
ObjectMapper objectMapper=new ObjectMapper();
try
{
objectMapper.writeValue(new File("E:/Project/SpringHibernet/wagafashionLatest/temp.json"), list);
}
catch (IOException ex){}
The file temp.json contains the following string.
[[21,"Gujarat"],[22,"Maharashtra"],[23,"Kerala"],[24,"New Delhi"]]
In both the cases (with both frameworks). So, it appears that the JSON response should be same in both the cases.
The temp.json file can also be deserialized as follows.
try
{
ObjectMapper mapper=new ObjectMapper();
List<Object[]> list = mapper.readValue(new File("E:/Project/SpringHibernet/wagafashionLatest/temp.json"), new TypeReference<List<Object[]>>() {});
for(Object[]o:list)
{
System.out.println(o[0]+" : "+o[1]);
}
}
catch (IOException ex)
{
}
It works fine and the foreach loop iterates over the List of type List<Object[]>. So, the problem might be caused by the Spring framework itself. What else is required, I'm not sure. Why is it not mapped by Jackson?
I have the same post on the Spring forum. The solution from the replies to the question which ultimately worked for me was required to configure the dispatcher-servlet.xml file as follows.
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager" />
<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="favorPathExtension" value="false" />
<property name="favorParameter" value="false" />
<property name="ignoreAcceptHeader" value="false" />
<property name="mediaTypes" >
<value>
atom=application/atom+xml
html=text/html
json=application/json
*=*/*
</value>
</property>
</bean>
This led JSON to work with Jackson 1.9.8 and Spring 3.2.0. This is credited to all the replies to that question.
My entire dispatcher-servlet.xml file now looks like the following.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="controller" />
<context:component-scan base-package="validatorbeans" />
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager" />
<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="favorPathExtension" value="false" />
<property name="favorParameter" value="false" />
<property name="ignoreAcceptHeader" value="false" />
<property name="mediaTypes" >
<value>
atom=application/atom+xml
html=text/html
json=application/json
*=*/*
</value>
</property>
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index.htm">indexController</prop>
</props>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
</beans>
I'm using Spring 3.1.3 and I've found that the Jackson mapping attempts to create a root object in the response. This is with the Jackson2 mapper. I haven't tried with the older Jackson mapper. If you also upgraded Jackson you may be seeing the same issue.
In the past, an object array would be mapped something like
[{name:'name1',id:4},{name:'name2',id:6}]
Now I find that they are providing an auto-generated object name for the object, so it is returned something like
{ objectArray: [{name:'name1',id:4},{name:'name2',id:6}]}
So you need to reference response.objectArray[0] instead of being able to directly reference response[0]
In any case, it's probable that the JSON response has changed format somewhat. You should look at the new response and see what changes need to occur in the javascript to make it map the new structure.

Resources