Jackson InvalidFormatException: Cannot deserialize value of type `java.util.UUID` from String - jackson

Am using Spring boot with a Rest Controller. I have a #PostMapping with a #RequestBody having object that has id of type UUID. When I am trying to test my post request from Postman I get the following error.
JSON parse error:
Cannot deserialize value of type java.util.UUID from String "4be4bd08cfdf407484f6a04131790949": UUID has to be represented by standard 36-char representation; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type java.util.UUID from String "4be4bd08cfdf407484f6a04131790949": UUID has to be represented by standard 36-char representation
I read in some post that talked about invalidFormatException but with a different data type that need to write some kind of Adapter. How can I resolve this for the UUID? Thanks in advance for your input.
#PostMapping(value = "/save_order")
#ResponseStatus(HttpStatus.CREATED)
public void postOrder(#RequestBody Order order) {
...
public class Order {
#Id
private UUID dstId;
....

Never mind, I searched around and was able to resolve the issue. Below is the solution.
So basically the solution was to remove the ID from the JSON that I was using for the request body. The Json that I was using earlier had dstId as the first key, removing it resolved my error.
{
"dstId":"4be4bd08cfdf407484f6a04131790949",
...
}
Also I realized that the root cause was that the data I was using above is not a valid UUID. Using a valid UUID in it's place worked, for example
"dstId": "110841e3-e6fb-4191-8fd8-5674a5107c33
The post that helped me to figure out Spring Boot JSON parse error: Cannot deserialize error

Related

can not send int to respond in ktor

I'm trying to send int response but get an error but when I use both as a string then response get successfully.
post("/employee") {
call.respond(mapOf("hey" to "Hey","if" to 1))
}
LOGCAT
java.lang.IllegalStateException: Serializing collections of different element types is not yet supported. Selected serializers: [kotlin.String, kotlin.Int]
at io.ktor.serialization.kotlinx.SerializerLookupKt.elementSerializer(SerializerLookup.kt:45)
at io.ktor.serialization.kotlinx.SerializerLookupKt.guessSerializer(SerializerLookup.kt:29)
at io.ktor.serialization.kotlinx.KotlinxSerializationBase.serialize$ktor_serialization_kotlinx(KotlinxSerializationBase.kt:34)
at
You can't pass different types in response "yet" like mentioned in stacktrace. As a workaround you can pass 1 as string or create custom class for this response and serialize it to json and send it like that

Ktor returns 415 from endpoints where receive() is used with ContentNegotiation

I have parameter classes with the #Searializable annotation:
#Serializable
data class ShowPostURL(
val date: String,
val titleSlug: String,
override val redirectTo: String? = null
)
and no matter what I do call.receive() won't work. I'm getting HTTP 415 errors and Ktor doesn't log anything. I've added the serialization support as well:
install(ContentNegotiation) {
json()
}
How do I fix this? This is how I'm trying to use it:
accept(ContentType.Any) {
get("/foo/{date}/{titleSlug}") {
val input = call.receive(ShowPostURL::class)
call.respondText("foo")
}
}
If I do a trace I can see that my route is matched, but it can't receive the parameters. Is this json() setup is supposed to work when I'm deserializing from url parameters like this?
Firstly, ContentNegotiation feature works only for receiving custom objects from the payload of POST, PUT and PATCH requests:
POST, PUT and PATCH requests have an associated request body (the payload). That payload is usually encoded.
In order to receive custom objects from the payload, you have to use the ContentNegotiation feature. This is useful for example to receive and send JSON payloads in REST APIs.
When receiving, the Content-Type of the request will be used to determine which ContentConverter will be used to process that request
Secondly, there are three out of the box ContentConverter available:
GsonConverter, JacksonConverter and SerializationConverter.
Each of these converters has its own configuration function: gson, jackson and serialization respectively. You use json configuration function which is most likely is not appropriate for the configuration of ContentNegotiation.
To solve your problem you can access URL parameters by referring them with call.parameters and manually create ShowPostURL object. Then serialize it with the kotlinx.serialization framework if needed.
Also, you can write your own ContentConverter to implement custom logic for receiving typed objects.

Implicit cast operator in ActionResult<bool> not working

I am following this guide to build my controllers. I do the following.
This is my controller:
// GET api/sth/{sthId}/isValid
[HttpGet("{sthId: int}/isValid")]
[ProducesResponseType(StatusCodes.Status200OK)]
[MyAuthorizeFilter]
public ActionResult<bool> Whatever(int sthId)
{
return this.myService.Whatever(sthId);
}
Theoretically, this should be converted to an Ok() ActionResult. However, If I write the following unit test:
[Fact]
public void Whatever()
{
this.myServiceMock.Setup(x => x.Whatever(It.IsAny<int>())).Returns(true);
-> I DEBUG HERE -> var result = this.myController.Whatever(1);
Assert.IsType<OkObjectResult>(result);
Assert.True((bool)result.Value);
}
I see that my result is an ActionResult<bool> indeed, whose Value is true as expected, but result.Result is null. So: no Ok action result whatsoever.
What am I missing? Do I have to write explicitly the return Ok() to get it? With the sentence
Implicit cast operators support the conversion of both T and ActionResult to ActionResult<T>. T converts to ObjectResult, which means return new ObjectResult(T); is simplified to return T;.
in the documentation I thought it was not necessary...?
The ActionResult<TValue> class:
wraps either an[sic] TValue instance or an ActionResult.
See also the source, its constructors assign either Value or Result, never both.
The MVC pipeline will assign a success status code to the response if no status code was explicitly set. But I can't find documentation for that claim.
This means the response as obtained in this test won't have a status code or OkActionResult anywhere. You can convert it to an ObjectResult, but that won't have a status code.
If you use something like swagger you will indeed get an OK from the server.
This happens to you because you dont perform an http request you simple call a method(your controller method) and you get a return type. You dont create a web server or something so no http status code is generated by .net core.
If you want to get status codes you should write test using http requests. Generally you could look up something like postman to perform your testing.

how to see actual body sent from restassured

I have created a jax-rs rest api and tested it with rest-assured. All tests are green. Now I am trying to create an html/js front end for it.
My problem is I do not know how my json objects should look like to be accepted by my rest api. Thanks to restassured/jax-rs I never handled request strings. I fill in objects and I get objects, (un)marshaling (json) is invisible.
Is there any way I can see (debug) what strings are created by rest-assured/java and sent over the "wire"?
If you want to log the request body you can do:
given().log().body(). ..
Or if you want to log the response body you can do:
.. .then().log().body(). ..
See documentation on logging for more details.
I'm not a RestAssured used, so I can't answer your question directly, but here are some ideas that may help you out.
I don't know what serializer RestAssured uses under the hood, but Resteasy on Wildfly uses Jackson by default. I would get familiar with this library. For less trivial application, you may need to dig into its APIs directly to get your desired results. Here is it's documentation. For your particular case you can do something as simple as
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(yourObject);
System.out.println(jsonString);
This will print out the POJO in JSON format, based on your getters in the class. This is at the most basic level. If you don't already have Jackson as a dependency, you can add
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.0</version>
</dependency>
A really good friend (tool) to have is cURL. It's a command line tool that allows you to make REST/HTTP (other protocols also) requests. Though for this particular case it wouldn't help, you could send a GET request to one your resources that serves up the same type that you accepted in your POST. That way, you can see the resulting JSON. This may be a little much at this point, but I would definitely look into this tool if you're going to be doing a lot of REST development.
You might also want to check out a Browser tool like [Postman for Chrome]
You should really get familiar with JSON format. Once you get familiar with it, and you start working with JSON framework, you'll notice that at a basic level, they all work similarly.
Java Object == JSON Object ( {} )
Java Collection/Array == JSON Array ( [] )
Java fields/properties == JSON keys
Getters are used for they keys and their values (for serialization)
Setters are used for deserialization
So for example you have this class
public class Person {
String name;
List<Person> friends;
public String getName() { return name; }
public void setName(String name) { return name; }
// Getter and Setter for friends
}
An instance of Person would produce the following JSON
{
"name" : "Peeskillet",
"friends": [
{
"name": "Lebron James"
},
{
"name": "Steph Curry"
}
]
}
It's actually pretty simple once you get the hang of it.
Oh and another thing you can do is add a logging filter on the server side as mentioned here.
As far as working with Javascript, there is a JSON.stringify(javascriptObject) that will serialize your Javacript objects to JSON strings. So generally, you can model your Javascript object like your Java objects.
Hope this helped.
In RestAssured just use this:
String body = resp.asString();
System.out.println(body);
Try this for Request Body
RequestSpecification httpRequest = RestAssured.given().urlEncodingEnabled(true);
..
..
..
System.out.println(" Body ==> "+ httpRequest.log().body());
And for response body:
System.out.println("Res Body ===>"+ response.getBody().prettyPrint());

Unable to add body to RestSharp RestRequest using enums

I am using RestSharp in ASP .NET MVC 2 project. Trying to create RestRequest (using POST method) and add two enum values (my enum type -- OrderStatusFlags) to request body -- using build-in RestSharp XmlSerializer:
var request = new RestRequest("orders/{vendorID}/{number}", Method.POST);
request.AddBody(previousOrderStatus);
request.AddBody(newOrderStatus);
But after calling AddBody method in request parameters can see only empty but no value. And while calling MVC action method an error occurs:
The parameters dictionary contains a null entry for parameter 'previousStatus' of non-nullable type 'OrderStatusFlags' for method 'RestResponse PostOrderStatus(Int32, System.String, OrderStatusFlags, OrderStatusFlags)' in 'OrdersResourceEndpoint'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
Enum look like this:
public enum OrderStatusFlags : long
{
Pending,
Confirmed,
...
}
Does anybody occurs a similiar situation?
A couple issues here. First, you can only call AddBody() once or the last call will take precedence. AddBody() is also only for sending XML as the request body. What is the required XML schema that you need to send to that URL? Can you post some sample XML that you're trying to generate?
I think more likely you actually want to use AddParameter() to add some POST parameters since that is far more common than XML request bodies.