Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error in SWAN JSON Deserializer #240

Closed
AppsmithsLLC opened this issue Feb 11, 2020 · 10 comments
Closed

Error in SWAN JSON Deserializer #240

AppsmithsLLC opened this issue Feb 11, 2020 · 10 comments
Labels
external Related to a problem external to SWAN (user code, other libraries...) v2.x Related to version 2 wontfix

Comments

@AppsmithsLLC
Copy link

AppsmithsLLC commented Feb 11, 2020

Describe the bug
When deserializing JSON using var data = await HttpContext.GetRequestDataAsync<SignInRequest>(); a new object is initialized, but the properties are all null.

To Reproduce
Make a POST request:
```
public static async Task PostAsJsonAsync(this HttpClient httpClient, string url, T data, CancellationToken cancellationToken = default)
{
var json = JsonNetSerializer.Serialize(data);
var content = new StringContent(json, Encoding.UTF8, "application/json");
return await httpClient.PostAsync(url, content, cancellationToken);
}

    [Route(HttpVerbs.Post, "/identity/signin/")]
    public async Task<SignInResponse> SignIn()
    {
        try
        {
            var data = await HttpContext.GetRequestDataAsync<SignInRequest>();
            return new SignInResponse {
                Result = SignInResult.Succeeded,
                Message = $"All good, {data.UserName}",
                DeviceId = $"{data.DeviceId}",
                AccessToken = "12345678"
            };
        }
        catch (Exception ex)
        {
            return new SignInResponse
            {
                Result = SignInResult.Failed,
                Message = ex.Message
            };
        }
    }

**Smartphone (please complete the following information):**
 - Device: iPhone 11
 - OS: 13.3

**Additional context**
Building the EmbedIO service within the context of a Xamarin.Forms app running on iOS.
@geoperez
Copy link
Member

Can you post a sample JSON and the definition of the class SignInRequest?

@rdeago
Copy link
Collaborator

rdeago commented Feb 11, 2020

@AppsmithsLLC posted on Slack before opening this issue, giving the following sample JSON:

{
  "userName": "Tester",
  "password": "QAIsGood",
  "deviceId": null
}

We still need the definition of SignInRequest though.

@AppsmithsLLC
Copy link
Author

SignInRequest Model:

namespace Identity.Api.Abstractions
{
    public class SignInRequest
    {
        public string UserName { get; set; }
        public string Password { get; set; }
        public string DeviceId { get; set; }
    }
}

@geoperez
Copy link
Member

The issue is because of the case, you need to specify that you are using camelCase instead of PascalCase.

https://unosquare.github.io/swan/api/Swan.Formatters.Json.html#Swan_Formatters_Json_Deserialize_System_String_Swan_JsonSerializerCase_

@AppsmithsLLC
Copy link
Author

@geoperez would you be able to cite an example of how to do this? Since I am using HttpContext.GetRequestDataAsync<T>() I'm not given the option to specify case.

@rdeago
Copy link
Collaborator

rdeago commented Feb 11, 2020

@AppsmithsLLC the request deserializer callback to use can be specified at Web API module level, like this:

var server = new WebServer("http://*:8080")
    .WithWebApi("/api", RequestDeserializer.Json, m => m
        .WithController<MyController>());

Or it can be given as a parameter to GetRequestDataAsync<>, like this:

var myData = HttpContext.GetRequestDataAsync<MyData>(RequestDeserializer.Json);

Unfortunately, there's currently no way to specify parameters for the JSON deserializer. Now for one of the most hated sentences in IT: it will be implemented in next version. 😬

As a workaround, since you already use JSON.NET in your project, you can use it for deserializing request bodies too. Just add this to your project:

using System;
using System.Threading.Tasks;
using EmbedIO;
using Newtonsoft.Json;
using Swan.Logging;

namespace YOUR_NAMESPACE_HERE
{
    /// <summary>
    /// Provides alternative request deserialization callbacks.
    /// </summary>
    public static class OtherRequestDeserializer
    {
        /// <summary>
        /// Asynchronously deserializes a request body in JSON format, using JSON.NET.
        /// </summary>
        /// <typeparam name="TData">The expected type of the deserialized data.</typeparam>
        /// <param name="context">The <see cref="IHttpContext"/> whose request body is to be deserialized.</param>
        /// <returns>A <see cref="Task{TResult}">Task</see>, representing the ongoing operation,
        /// whose result will be the deserialized data.</returns>
        public static async Task<TData> NewtonsoftJson<TData>(IHttpContext context)
        {
            using (var reader = context.OpenRequestText())
			using (var jsonReader = new JsonTextReader(reader))
            {
				var serializer = new JsonSerializer();
				try
				{
					return Task.FromResult(serializer.Deserialize<TData>(jsonReader));
				}
				catch (Exception)
				{
					$"[{context.Id}] Cannot convert JSON request body to {typeof(TData).Name}, sending 400 Bad Request..."
						.Warn($"{nameof(OtherRequestDeserializer)}.{nameof(NewtonsoftJson)}");

					throw HttpException.BadRequest("Incorrect request data format.");
				}
            }
        }
    }
}

Then you can do this:

var server = new WebServer("http://*:8080")
    .WithWebApi("/api", OtherRequestDeserializer.NewtonsoftJson, m => m
        .WithController<MyController>());

or this:

var myData = HttpContext.GetRequestDataAsync<MyData>(OtherRequestDeserializer.NewtonsoftJson);

@rdeago rdeago self-assigned this Feb 11, 2020
@rdeago rdeago added enhancement v2.x Related to version 2 external Related to a problem external to SWAN (user code, other libraries...) and removed enhancement labels Feb 11, 2020
@rdeago rdeago removed their assignment Feb 11, 2020
@geoperez
Copy link
Member

Can I close this issue?

@namilkimfree
Copy link

i use to code but not JsonSerializerCase.CamelCase

Only SerializerCase PascalCase...

my Json object
internal class OldDefaultResponse<T> : ResponseBase<T> { public T Nfcuuid { get; set; } }
and server init
_server = new WebServer(6329) .WithWebApi("/api", MainController.Json ,m => m .WithController(() => new MainController(_printservice)));

and MainController.Json method

public static async Task Json(IHttpContext context, object data) { context.Response.ContentType = MimeType.Json; using (var text = context.OpenResponseText(new UTF8Encoding(false))) { await text.WriteAsync(Swan.Formatters.Json.Serialize(data, Swan.Formatters.JsonSerializerCase.CamelCase)).ConfigureAwait(false); } }

Result Json string Case: PascalCase

@stale
Copy link

stale bot commented May 9, 2020

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

@stale stale bot added the wontfix label May 9, 2020
@stale stale bot closed this as completed May 16, 2020
@Guifgr
Copy link

Guifgr commented Aug 27, 2021

var bodyAsString = await HttpContext.GetRequestBodyAsStringAsync();
var data = Json.Deserialize(bodyAsString, JsonSerializerCase.CamelCase);

This should resolve your problem

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
external Related to a problem external to SWAN (user code, other libraries...) v2.x Related to version 2 wontfix
Projects
None yet
Development

No branches or pull requests

5 participants