Change the default REST response to JSON instead XML - json

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....

Related

Camel binding mode for JSON not working, cant unmarshal it to POJO

I'm trying to send message from rest API to new route, and even thou I receive request in JSON format on my REST API and binding is set to JSON, when I forward it to new route it will be shown as InputStream and I will have to marshal it to JSON in order to use it.
I already tried using streamCaching and other components in RestConfiguration (consumes, produces, type, dataType). Also i'm using all dependencies in POM.
public void configure() {
restConfiguration().component("servlet")
.bindingMode(RestBindingMode.json)
.skipBindingOnErrorCode(false);
rest("/resttest")
.patch("/t1")
.id("t1")
.description("t1")
.consumes("application/json")
.produces("application/json")
.param()
.name("body")
.type(RestParamType.body)
.dataType("json")
.required(true)
.endParam()
.to("direct:test2");
This route is in other class:
from("direct:test2").id("test2")
.marshal().json(JsonLibrary.Jackson,SomePOJO.class)
.unmarshal().json(JsonLibrary.Jackson, SomePOJO.class)
.choice()
.when(simple("${body.getStatus()} =~ 'Closed'"))
.....
I was expecting to get JSON message on test2 route, and somehow I get InputStream, so i have to do marshaling first. Anybody know how I can make REST API forward me to route message in JSON format, not as stream?
Try:
.convertBodyTo(String.class)
before your unmarshal.
I was having the same issue, and I had to apply the marshal method for incoming values and unmarshal method for response.
This was the response in postman:
And I was using this code:
rest(service.service)
.description(ContentCategory.api("Service Test"))
.post("/product/{productType}/{enterpriseId}")
.description("service for saving a product")
.consumes(MediaType.APPLICATION_JSON)
.type(Product.class)
.bindingMode(RestBindingMode.json)
.produces(MediaType.APPLICATION_JSON)
.outType(String.class)
.route()
.bean("productService", "saveProduct")
.marshal()
.json(JsonLibrary.Jackson)
.setHeader(Exchange.CONTENT_TYPE, constant(MediaType.APPLICATION_JSON))
.endRest();
I just added the unmarshall method after realizing that I was receiving an InputStream
rest(service.service)
.description(ContentCategory.api("Service Test"))
.post("/product/{productType}/{enterpriseId}")
.description("service for saving a product")
.consumes(MediaType.APPLICATION_JSON)
.type(Product.class)
.bindingMode(RestBindingMode.json)
.produces(MediaType.APPLICATION_JSON)
.outType(String.class)
.route()
.bean("productService", "saveProduct")
.marshal()
.json(JsonLibrary.Jackson)
.unmarshal()
.json(JsonLibrary.Jackson)
.setHeader(Exchange.CONTENT_TYPE, constant(MediaType.APPLICATION_JSON))
.endRest();
In fact, I just added this two lines
.unmarshal()
.json(JsonLibrary.Jackson)
And it starts working:
It think is probably you need to use the unmarshal method for the resttest service.

Bad Request response when passing a JSON in process variables - flowable

I'm using flowable and try to pass a JSON as body, but it's seen as malformed when processing the request (or so I think since the error is Bad Request). Basically I'm passing some parameters this way:
#PostMapping(path = PathConstants.START_ACTION)
public ResponseEntity<BaseResponse<ProcessInstance>> start(#PathVariable String processDefinitionId,
#RequestBody(required = false) Map<String, Object> params)
The params are set using postman, this way:
{
"body": {
"email":"testmail#test",
"password":"password"
}
}
The process starts and the POST call is made, but Bad Request is given back. I've tried printing the variables of the process after this call and this is what I have:
body={email=testmail#test, password=password}
So I've tried passing this instead:
{
"body": "{ \"email\":\"testmail#test\", \"password\":\"password\"}"
}
And when printing the variables I have:
body={"email":"testmail#test", "password":"password"}
but still it's a bad request. What is wrong with this JSON?
If you want to pass a variable that is a JSON then you would need to make sure that body is type JsonNode from Jackson.
Looking at your request signature Map<String, Object>, Jackson would contain a map of maps.
I don't know what you are trying to do. However, I would highly advise you to work with predefined parameters in your REST API. If you need something generic you can use the REST API of Flowable to do what you want to do.

How can I define a ReST endpoint that allows json input and maps it to a JsonSlurper

I want to write an API ReST endpoint, using Spring 4.0 and Groovy, such that the #RequestBody parameter can be any generic JSON input, and it will be mapped to a Groovy JsonSlurper so that I can simply access the data via the slurper.
The benefit here being that I can send various JSON documents to my endpoint without having to define a DTO object for every format that I might send.
Currently my method looks like this (and works):
#RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<String> putTest(#RequestBody ExampleDTO dto) {
def json = new groovy.json.JsonBuilder()
json(
id: dto.id,
name: dto.name
);
return new ResponseEntity(json.content, HttpStatus.OK);
}
But what I want, is to get rid of the "ExampleDTO" object, and just have any JSON that is passed in get mapped straight into a JsonSlurper, or something that I can input into a JsonSlurper, so that I can access the fields of the input object like so:
def json = new JsonSlurper().parseText(input);
String exampleName = json.name;
I initially thought I could just accept a String instead of ExampleDTO, and then slurp the String, but then I have been running into a plethora of issues in my AngularJS client, trying to send my JSON objects as strings to the API endpoint. I'm met with an annoying need to escape all of the double quotes and surround the entire JSON string with double quotes. Then I run into issues if any of my data has quotes or various special characters in it. It just doesn't seem like a clean or reliable solution.
I open to anything that will cleanly translate my AngularJS JSON objects into valid Strings, or anything I can do in the ReST method that will allow JSON input without mapping it to a specific object.
Thanks in advance!
Tonya

ContentType application/json in ASP.NET WebAPI

I'm building my first WebAPI using ASP.NET MVC 4 WebAPI.
The requests must be sent using the application/json ContentType with utf-8 as the character set.
My POST method looks like this:
public HttpResponseMessage Post([FromBody]string value)
{
return new HttpResponseMessage(HttpStatusCode.OK);
}
Whenever I'm sending a POST request the parameter 'value' is null. The request body contains Json: { "name":"test" }.
What I prefer is to have the parameter of the Post method to be either a string containing the Json or be of type JObject (from the JSON.NET library). How do I accomplish this? And is this even possible?
The easiest way is to grab the raw string directly from Request.Content:
public async Task<HttpResponseMessage> Post()
{
string value = await Request.Content.ReadAsStringAsync();
return new HttpResponseMessage(HttpStatusCode.OK);
}
There is a way to make ASP.NET Web Api treat your request body as string content, but in order to do that the content must be in =value format, in your case something like this:
={ "name":"test" }
You can achieve something like this with following jQuery code (for example):
$.post('api/values', '=' + JSON.stringify({ name: 'test' }));
In that case you can use signature from your question.
In the end there is always an option of creating your own MediaTypeFormatter to replace the default JsonMediaTypeFormatter and make it always deserialize the content into JObject. You can read more about creating and registering MediaTypeFormatter here and here.

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);