Howto use Spring Resttemplate with JSON only - json

I have a rest-service which provides information in XML or JSON. I connect my application to this service with Spring Resttemplate. Unfortunately my responses are all in XML instead of the prefered JSON format. My analysis of the requests is, that Spring Resttemplate sends the request with the following Accept-Header:
Accept: application/xml, text/xml, application/*+xml, application/json
My rest-service response with the first accepted type. This is allways application/xml.
How can I change the Accept-Types so that I only get json responses? Are there some properties for this in the bean-definition of RestTemplate?
I use Spring 3.1 for this.

You need to set a list of HttpMessageConverters available to RestTemplate in order to override the default one:
RestTemplate rest = new RestTemplate();
rest.setMessageConverters(Arrays.asList(new MappingJacksonHttpMessageConverter()));
If you define RestTemplate in XML, do the same thing in XML syntax.

Not so clear from the topic if you want to consume JSON only or send.
In first case (consuming) you can annotate your Controller with
#RequestMapping(value="/path", headers = "Accept=application/json")
In case of producing you have to for ResponseEntry with contentType:
HttpHeaders headers = new HttpHeaders();
headers.add("Accept", "application/json");
ResponseEntity.status(HttpStatus.OK)
.contentType(MediaType.APPLICATION_JSON)
.headers(headers);

Related

Passing Json status code in Springboot+Angular

Is there any way to pass a Json status/response from Springboot to Angular service? Let’s say, beside the Httpstatus sent on Response Entity, I want also to send a Json response. Thanks
Or maybe a second question is how to use the Http status from Spring boot, in Angular service.
From your springboot endpoint, you can send JSON response along with the HttpStatus
Below is the sample code
#GetMapping(value = "/getUserDetails" , produces = "application/json")
public ResponseEntity getUserDetails(){
userDetails = userService.getUserDetails();
return ResponseEntity.status(HttpStatus.OK).body(userDetails);
}
This is how you can return userDetails object which will be converted to JSON automatically as we used produces = "application/json"

Posting Json as Entity with scalaj-http

the api of scalaj-http is clean and I would like to use it for a new project, but it usually post a Json in StringEntity as parameter, like this
JSONObject TokenRequest = new JSONObject()
.put("Credentials", new JSONObject()
.put("Username", username)
.put("Password", password));
StringEntity requestBody = new StringEntity(TokenRequest.toString());
httppost.setEntity(requestBody);
Not sure if it doable with scalaj-http?
According to their github page you need to set the content-type header to application/json to send the body as json.
Http(url).postData(data).header("content-type", "application/json").asString.code

Change the default REST response to JSON instead XML

I'm pretty new with Java REST, I'm currently confused with the response I'm getting from POSTMAN or Chrome is always defaulted to XML and could not change it to JSON unless I remove the XML part. I'm using Jersey 2, Netbeans and Glassfish 4.1.1/4.1
This only returns XML
#Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
This will return JSON only
#GET
#Path("loc/{lat}/{long}")
#Produces({MediaType.APPLICATION_JSON})
#SuppressWarnings("unchecked")
//#Produces({MediaType.TEXT_PLAIN})
public List<Lastknown> findNearMeLastKnown(#PathParam("lat") String lat, #PathParam("long") String longitude) {
//List<Lastknown> results =;
return super.findNearMeLastKnown(lat,longitude);
}
A quick guess, you have to add the following header in POSTMAN:
Accept: application/json
Otherwise the server doesn't know which format you want....

Submitting multipart/form with JSON with Ext-JS to JAX-RS, How to set Content-Type?

I want to submit a form that has file attachment using Ext-JS to a JAX-RS service that is using Jackson to process the JSON.
The problem that i have is that the JSON data doesn't have a Content-Type and I don't know how to set it?
Currently the request body looks something like the following:
-----------------------------4664151417711
Content-Disposition: form-data; name="productBinary"; filename="new.txt"
Content-Type: text/plain
blah
-----------------------------4664151417711
Content-Disposition: form-data; name="myData"
{"MyData": [1,2,3] }
-----------------------------4664151417711--
All good, except that the JSON section doesn't have a Content-Type and therefore I can't get the JAX-RS service to deserialise the JSON into an object
The JAX-RS service is something like:
#POST
#Path("/submit")
#Consumes("mulitipart/form-data")
public String submit( MultipartBody body )
{
MyData myData = body.getAttachmentObject("myData",MyData.class);
return "done";
}
any ideas?
UPDATE:
seems that there is no 'nice' way of doing this, instead I found that i need to call the json deserializer directly.
ObjectMapper om = new ObjectMapper();
InputStream is = body.getAttachment("myData").getDataHandler().getInputStream()
MyData md = om.readValue(is,MyData.class);

how to receive a string in C# JSON Webservice that uses JSON.net

I have a working webservice that uses C# to exchange JSON data with an Android Device (thank you GSON!). The method ultimately returns a valid JSON response.
[WebMethod(EnableSession = true,Description="My Description")]
public string PostBatchData(Batchdata batchdata)
{
// my method
return JSONstring;
}
I want to use JSON.net so I can do error checking, etc. My question is: How should I cast the object (this is receiving JSON in the HTML POST) to string so I can use JSON.net to parse the POST? I've tried
public string PostBatchData(string batchdata){}
but this approach isn't working (probably looking for arguments in the URL).
The excerpt below is what Fiddler is catching... (I've edited for brevity).
POST http://www.myurl.com/JSONHandler.asmx/PostBatchData HTTP/1.1
Accept: application/json
Content-type: application/json
Content-Length: 2088
Content-Type: application/json
Host: www.myurl.com
Connection: Keep-Alive
{"batchdata":{"uname":"user1... }
Within the method, I think I want to use something like:
var container = Test.DeserializeFromJson<RootObject>(jsonstring);
but I am asking for a hint on how to populate jsonstring from the HTTP POST.
You can Deserialize the Batchdata object to JSON first.
string json = JsonConvert.DeserializeObject(batchdata);