Return a JSONObject through Spring MappingJackson2JsonView - json

I Have xml and json output view for my spring project. I'm using spring 4 version and This is the my ViewResolver xml file.
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1" />
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
</map>
</property>
<property name="defaultViews">
<list>
<!-- JSON View -->
<bean
class="org.springframework.web.servlet.view.json.MappingJackson2JsonView">
</bean>
<!-- JAXB XML View -->
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>com.rest.dto.SportInfoDtoList</value>
</list>
</property>
</bean>
</constructor-arg>
</bean>
</list>
</property>
<property name="ignoreAcceptHeader" value="true" />
</bean>
I want to pass Jackson JSONObject through my controller using ModelAndView.
#RequestMapping(value="stat", method=RequestMethod.POST)
public ModelAndView getSeasonteamStat(#ModelAttribute(value="statDto") StatDto statDto){
ModelAndView model = new ModelAndView();
try{
String seasonteamstatStr = GuideStatClient.getSeasonTeamStats();
JSONObject seasonteamstat = new JSONObject(seasonteamstatStr);
model.addObject("seasonteamstat", seasonteamstat);
return model;
} catch (Exception e){
return model;
}
}
If I return seasonteamstatStr it will return successfully. But I need to pass this string as a json objet. This is a huge object so I dont want to map it into java objects using JAXB.
So is there have any way to pass this string as a json. I tried jackson and gson JSONObject. Thanks in advance

Annotate your method with #ResponseBody which indicates a method return value should be bound to the web response body and change the return type to String

Related

Spring batch read from xml file and write to Database. need step1 auto generated key for step2

As seen in below code in step1 I'm reading users.xml and writing to database now in step2 I'm reading from userdetails.xml and writing to database but I need step1 auto generated key of tbl_user for step2. How Can I do that?
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:batch="http://www.springframework.org/schema/batch"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/batch
http://www.springframework.org/schema/batch/spring-batch-2.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
<import resource="../config/context.xml" />
<import resource="../config/database.xml" />
<bean id="xmlItemReader1" class="org.springframework.batch.item.xml.StaxEventItemReader">
<property name="resource" value="file:xml/outputs/users.xml" />
<property name="fragmentRootElementName" value="user" />
<property name="unmarshaller" ref="userUnmarshaller"/>
</bean>
<bean id="xmlItemReader2" class="org.springframework.batch.item.xml.StaxEventItemReader">
<property name="resource" value="file:xml/outputs/userdetails.xml" />
<property name="fragmentRootElementName" value="userdetail" />
<property name="unmarshaller" ref="userUnmarshaller"/>
</bean>
<bean id="itemProcessor1" class="com.qmetry.recovery.mapper.UserItemProcessor" />
<bean id="itemProcessor2" class="com.qmetry.recovery.mapper.UserDetailItemProcessor" />
<job id="testJob2" xmlns="http://www.springframework.org/schema/batch">
<step id="step2_1">
<tasklet transaction-manager="transactionManager">
<chunk reader="xmlItemReader1" writer="databaseItemWriter1" processor="itemProcessor1"
commit-interval="100" />
</tasklet>
<listeners>
<listener ref="testListener" />
</listeners>
</step>
<step id="step2_2">
<tasklet transaction-manager="transactionManager">
<chunk reader="xmlItemReader2" writer="databaseItemWriter2" processor="itemProcessor1"
commit-interval="100" />
</tasklet>
</step>
</job>
<bean id="testListener" class="com.qmetry.recovery.mapper.TestListener" scope="step" />
<bean id="databaseItemWriter1" class="org.springframework.batch.item.database.JdbcBatchItemWriter">
<property name="dataSource" ref="dataSource" />
<property name="sql">
<value>
<![CDATA[
insert into TBL_USER(USERNAME,EMAILID)
values (?, ?)
]]>
</value>
</property>
<!--We need a custom setter to handle the conversion between Jodatime LocalDate and MySQL DATE BeanPropertyItemSqlParameterSourceProvider-->
<property name="itemPreparedStatementSetter">
<bean class="com.qmetry.recovery.mapper.UserItemPreparedStatementSetter"/>
</property>
</bean>
<bean id="databaseItemWriter2" class="org.springframework.batch.item.database.JdbcBatchItemWriter">
<property name="dataSource" ref="dataSource" />
<property name="sql">
<value>
<![CDATA[
insert into TBL_USERDETAIL(USERID,CONTACT)
values (?, ?)
]]>
</value>
</property>
<!--We need a custom setter to handle the conversion between Jodatime LocalDate and MySQL DATE BeanPropertyItemSqlParameterSourceProvider-->
<property name="itemPreparedStatementSetter">
<bean class="com.qmetry.recovery.mapper.UserDetailItemPreparedStatementSetter"/>
</property>
</bean>
users.xml
<?xml version="1.0" encoding="UTF-8"?><users>
<user>
<userId>1</userId>
<userName>Taher</userName>
<emailId>taher.tinwala#hotmail.com</emailId>
</user>
</users>
userdetails.xml
<?xml version="1.0" encoding="UTF-8"?><userdetails>
<userdetail>
<userDetailId>1</userDetailId>
<userId__TblUser>1</userId__TblUser>
<contact>1111111111</contact>
</userdetail>
<userdetail>
<userDetailId>2</userDetailId>
<userId__TblUser>1</userId__TblUser>
<contact>2222222222</contact>
</userdetail>
<userdetail>
<userDetailId>4</userDetailId>
<userId__TblUser>1</userId__TblUser>
<contact>4444444444</contact>
</userdetail>
</userdetails>
You need to pass data to a future step. For explantory documentation see http://docs.spring.io/spring-batch/trunk/reference/html/patterns.html#passingDataToFutureSteps
I have implemented the example from the documentation and adjusted it to your configuration with some assumptions here and there.
During the read (or the write, it depends when you get the data that you want to pass) in step 1 you need to store the data in the StepExecution. Add to your xmlItemReader the following:
public class YourItemReader implements ItemReader<Object>
private StepExecution stepExecution;
public void read(Object item) throws Exception {
// ...
ExecutionContext stepContext = this.stepExecution.getExecutionContext();
stepContext.put("tbl_user", someObject);
}
#BeforeStep
public void saveStepExecution(StepExecution stepExecution) {
this.stepExecution = stepExecution;
}
Your xml will look like this:
<step id="step2_1">
<tasklet transaction-manager="transactionManager">
<chunk reader="xmlItemReader1" writer="databaseItemWriter1" processor="itemProcessor1" commit-interval="100" />
</tasklet>
<listeners>
<listener ref="testListener" />
<listener ref="promotionListener"/>
</listeners>
</step>
Add the promotionListener bean:
<beans:bean id="promotionListener" class="org.springframework.batch.core.listener.ExecutionContextPromotionListener">
<beans:property name="keys" value="tbl_key"/>
</beans:bean>
And finally you need to retrieve the value in step 2. Again asuming you need it in the reader of step 2 you reader in step 2 needs the following code added:
public class YourItemReader2 implements ItemReader<Object>
private Object someObject;
#BeforeStep
public void retrieveInterstepData(StepExecution stepExecution) {
JobExecution jobExecution = stepExecution.getJobExecution();
ExecutionContext jobContext = jobExecution.getExecutionContext();
this.someObject = jobContext.get("tbl_key");
}
Now you have acces to the value read in step 1.
EDIT - adding some example configuration for an extra read step:
After step 1 add a simple step 2 with the following reader to get the new value from the database
<bean id="itemReader" class="org.springframework.batch.item.database.JdbcCursorItemReader"
scope="step">
<property name="dataSource" ref="dataSource" />
<property name="sql">
<value>
<![CDATA[
YOUR SELECT STATEMENT
]]>
</value>
</property>
<property name="rowMapper" ref="rowMapper" />
</bean>
And a simple rowMapper bean
<bean id="rowMapper" class="exampleRowMapper" />
You will have to write your exampleRowMapper obviously to reflect the data your fetching. For example:
public class ExampleRowMapper implements ParameterizedRowMapper<String> {
#Override
public String mapRow(ResultSet rs, int rowNum) throws SQLException {
return String.valueOf(rs.getString(1));
}
}
In your dummywriter you add the stepexecution and you will store your value in the step execution context.:
public class DummyItemWriter implements ItemWriter<Object> {
private StepExecution stepExecution;
#Override
public void write(List<? extends Object> item) throws Exception {
ExecutionContext stepContext = this.stepExecution.getExecutionContext();
stepContext.put("someKey", someObject);
}
}
And the bean for the writer:
<bean id="savingDummyWriter" class="your.package.DummyItemWriter" />
And wrap the reader and writer in a step.
<step id="step2">
<tasklet>
<chunk reader="itemReader" writer="dummyItemWriter" commit-interval="1" />
</tasklet>
<listeners>
<listener ref="promotionListener"/>
</listeners>
</step>

posting a JSON using Spring RestTemplate

I've converted a Java Object to json String and I am trying to post it to a rest webservice using RestTemplate and I am always getting a 500 error. The following are the details:
User createJSONUser = createUser(); // provides me the java object
//converting the javaobject to json string successfully using jackson in the next two lines
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(createJSONUser);
//creating the headers
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
requestHeaders.setAccept(Collections.singletonList(new MediaType("application","json")));
//setting the message converter
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
//posting the json using resttemplate
ResponseEntity<String> response = restTemplate.exchange(sandBoxURL, HttpMethod.POST, new HttpEntity<String>(jsonString, requestHeaders), String.class);
I am obtaining the resttemplate as a bean which is defined in my context-xml as follows:
<?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:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd">
<bean id="responseMessageConverter" class = "com.uhg.iam.esso.rest.client.converters.CustomResponseConverter">
<property name="supportedMediaTypes" value="application/xml"/>
</bean>
<bean id="customErrorHandlerForEssoRestServer" class="com.uhg.iam.esso.rest.client.EssoRestClientErrorHandler"/>
<bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean id="jaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="supportJaxbElementClass" value="true"/>
<property name="classesToBeBound">
<list>
<value>esso.schemas.core._1.Response</value>
</list>
</property>
</bean>
<bean id="marshallingHttpMessageConverter" class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
<property name="marshaller" ref="jaxb2Marshaller"/>
<property name="unmarshaller" ref="jaxb2Marshaller"/>
</bean>
<bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="prefixJson" value="false"/>
<property name="supportedMediaTypes" value="application/json"/>
</bean>
<bean id="restTemplateBean" class="org.springframework.web.client.RestTemplate">
<property name="errorHandler" ref="customErrorHandlerForEssoRestServer"/>
<property name="messageConverters">
<list>
<!-- <ref bean="marshallingHttpMessageConverter"/>
<ref bean="responseMessageConverter"/> -->
<ref bean="jsonHttpMessageConverter"/>
<ref bean="stringHttpMessageConverter"/>
</list>
</property>
</bean>
<bean id="essoRestClientDelegate" class="com.uhg.iam.esso.rest.client.EssoRestClientJSONDelegate">
<property name="restTemplate" ref="restTemplateBean"/>
</bean>
</beans>
Can someone please point out where I am making a mistake?

Spring REST: HttpMediaTypeNotSupportedException: Content type 'application/json;charset=UTF-8'

I am getting the above error, due to a problem with Jackson attempting to deserialize my POJO.
I've debugged the code and it returns false within Jackson's ObjectMapper:
public boolean canRead(Type type, Class<?> contextClass, MediaType mediaType) {
JavaType javaType = getJavaType(type, contextClass);
return (this.objectMapper.canDeserialize(javaType) && canRead(mediaType));
}
this.objectMapper.canDeserialize(javaType) returns false which causes the error
My Controller is as follows:
#Controller
public class CancelController {
#Autowired
private CancelService cancelService;
#RequestMapping( value="/thing/cancel", method=RequestMethod.POST, consumes="application/json" )
public #ResponseBody CancelThingResponseDTO cancelThing(#RequestBody CancelRequestDTO cancelThingRequest) {
return cancelService.cancelThing(cancelThingRequest);
}
My CancelRequestDTO implements Serializable:
public class CancelRequestDTO implements Serializable{
/**
* Default serialization ID
*/
private static final long serialVersionUID = 1L;
/**
* Reason code associated with the request
*/
private final String reasonCode;
/**
* Identifier of the entity associated with the request
*/
private final EntityIdentifier entityIdentifier;
/**
* Default constructor
*
* #param reasonCode Reason code associated with the request
* #param entityIdentifier Identifier of the entity associated with the request
*/
public CancelRequestDTO(String reasonCode, EntityIdentifier entityIdentifier) {
super();
this.reasonCode = reasonCode;
this.entityIdentifier = entityIdentifier;
}
/**
* #return Returns the reasonCode.
*/
public String getReasonCode() {
return reasonCode;
}
/**
* #return Returns the entityIdentifier.
*/
public EntityIdentifier getEntityIdentifier() {
return entityIdentifier;
}
}
My Spring configuration is as follow:
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<mvc:annotation-driven />
<!-- Scan for stereotype annotations -->
<context:component-scan base-package="com.cancel.web.controller" />
<bean id="viewNameTranslator"
class="org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator" />
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />
<bean id="jsonView"
class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" >
<property name="contentType" value="application/json;charset=UTF-8"/>
</bean>
<!-- Register JSON Converter for RESTful Web Service -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
</bean>
</list>
</property>
</bean>
Anyone know what might be causing this deserialization issue?
Thanks
Caused by my DTO not having a default constructor with setters! So looks like an inaccurate Exception from Jackson
For anyone who still facing this problem, you cannot have two #JsonBackReference in a single class, add value to one of the reference like this #JsonBackReference(value = "secondParent") also add the same value to #JsonManagedReference(value ="secondParent") in parent class.
I have always done this using the ContentNegotiatingViewResolver. It seems that it is not understanding the content type that you are passing it. This is the configuration that I typically use for doing what you are trying to do:
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1" />
<property name="contentNegotiationManager">
<bean class="org.springframework.web.accept.ContentNegotiationManager">
<constructor-arg>
<bean class="org.springframework.web.accept.PathExtensionContentNegotiationStrategy">
<constructor-arg>
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
</map>
</constructor-arg>
</bean>
</constructor-arg>
</bean>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.xstream.XStreamMarshaller">
<property name="autodetectAnnotations" value="true" />
</bean>
</constructor-arg>
</bean>
</list>
</property>
</bean>
This video goes through doing exactly what you are trying to do with consuming the service through jQuery in the UI:
http://pluralsight.com/training/Courses/TableOfContents/springmvc-intro

Spring json not using the desired root name

I have the following configuration :
<property name="defaultViews">
<list>
<!-- JSON View -->
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
<!-- XML View -->
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.xstream.XStreamMarshaller">
<property name="autodetectAnnotations" value="true" />
</bean>
</constructor-arg>
</bean>
</list>
</property>
It creates a json, but the root name is not what i want
#XStreamAlias("house")
#JsonAutoDetect
#JsonRootName(value = "house")
public class TableHouse {
private Long value;
.....
}
For the xml it works fine, however for the json it does not pick up the #JsonRootName.. and outputs json with class name as root...
Any ideas?
You have to enable root-level wrapping. See How do I rename the root key of a JSON with Java Jackson? to have an idea on how to use JsonRootName properly.

Spring configuration - mvc:annotation-driven, AnnotationMethodHandlerAdapter, and JSON

Thanks in advance any help.
I'm trying to get one of my controller methods to return JSON. Starting off with a simple test:
#RequestMapping(value="/myReqPath", method=RequestMethod.GET)
#ResponseBody
public Map<String, String> myJsonMethod() {
Map<String, String> response = new TreeMap<String, String>();
response.put("test", "test");
return response;
}
It's my understanding that I need <mvc:annotation-driven/> added to my servlet context to accomplish this. The problem is when I add it, it breaks my custom AnnotationMethodHandlerAdapter.
[B]How do I extract and add the needed parts of <mvc:annotation-driven/> to return JSON from the controller?[/B]
Here are the pertinent parts of my servlet config:
<!--Skipping this for now...
<mvc:annotation-driven/>
-->
<!-- JSON Marshaling -->
<util:constant id="jsonBasicClassIntrospector"
static-field="org.codehaus.jackson.map.introspect.BasicClassIntrospector.instance" />
<bean id="jsonJaxbAnnotationIntrospector"
class="org.codehaus.jackson.xc.JaxbAnnotationIntrospector" />
<bean id="jsonVisibilityChecker"
class="org.codehaus.jackson.map.introspect.VisibilityChecker.Std"
factory-method="defaultInstance" />
<bean id="jsonDefaultTypeFactory"
class="org.codehaus.jackson.map.type.TypeFactory"
factory-method="defaultInstance" />
<bean id="jsonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper">
<property name="serializationConfig">
<bean class="org.codehaus.jackson.map.SerializationConfig">
<constructor-arg ref="jsonBasicClassIntrospector" />
<constructor-arg ref="jsonJaxbAnnotationIntrospector" />
<constructor-arg ref="jsonVisibilityChecker" />
<constructor-arg><null/></constructor-arg>
<constructor-arg><null/></constructor-arg>
<constructor-arg ref="jsonDefaultTypeFactory" />
<constructor-arg><null/></constructor-arg>
</bean>
</property>
<property name="deserializationConfig">
<bean class="org.codehaus.jackson.map.DeserializationConfig">
<constructor-arg ref="jsonBasicClassIntrospector" />
<constructor-arg ref="jsonJaxbAnnotationIntrospector" />
<constructor-arg ref="jsonVisibilityChecker" />
<constructor-arg><null/></constructor-arg>
<constructor-arg><null/></constructor-arg>
<constructor-arg ref="jsonDefaultTypeFactory" />
<constructor-arg><null/></constructor-arg>
</bean>
</property>
</bean>
...
<!-- My custom AnnotationMethodHandlerAdapter... -->
<bean id="sessionArgResolver" class="com.SessionParamArgumentResolver"/>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="customArgumentResolver" ref="sessionArgResolver"/>
</bean>
As it stands, my controller method is invoked however, the browser returns http status 406:
406 Not Acceptable - [url]http://localhost:8080/myApp/myReqPath[/url]
If you already have a custom AnnotationMethodHandlerAdapter declaration, you can just add a list of HttpMessageConverters to it:
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="customArgumentResolver" ref="sessionArgResolver"/>
<property name = "messageConverters">
<list>
<bean
class = "org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name = "objectMapper" ref = "jsonObjectMapper" />
</bean>
</list>
</property>
</bean>