Newtonsoft

The package contains various different logic for working with Newtonsoft.Json (also referrred to as JSON.net).

NewtonsoftJsonResult

By default, if you return a model from an API controller, the model will be serialized using Microsoft.Text.Json.

If you wish to use JSON.net for serialization instead, you can use the Skybrud.Essentials.AspNetCore.Models.Json.JsonNetResult class to wrap your models.

The Skybrud.Essentials.AspNetCore.Json.Newtonsoft.NewtonsoftJsonResult class features a number of static initializers for the most common status codes:

200 OK

return NewtonsoftJsonResult.Ok(new { hello = "world" });

returns:

{
    "hello": "world"
}

201 Created

return NewtonsoftJsonResult.Created(new { hello = "world" });

returns:

{
    "hello": "world"
}

400 Bad Request

return NewtonsoftJsonResult.BadRequest("Nope");

returns:

{
    "meta": {
        "code": 400,
        "error": "Nope"
    }
}

401 Unauthorized

return NewtonsoftJsonResult.Unauthorized("Not authorized");

returns:

{
    "meta": {
        "code": 401,
        "error": "Not authorized"
    }
}

403 Forbidden

return NewtonsoftJsonResult.Forbidden("Forbidden");

returns:

{
    "meta": {
        "code": 403,
        "error": "Forbidden"
    }
}

404 Not Found

return NewtonsoftJsonResult.NotFound("Not Found");

returns:

{
    "meta": {
        "code": 404,
        "error": "Not Found"
    }
}

500 Internal Server Error

return NewtonsoftJsonResult.InternalError("Computer says no...");

returns:

{
    "meta": {
        "code": 500,
        "error": "Computer says no..."
    }
}

NewtonsoftJsonOnlyConfiguration

The NewtonsoftJsonOnlyConfigurationAttribute class is a special attribute that you may add to your API controllers, which then will result in the value being serlaized with Newtonsoft.Json. Eg. such as:

[NewtonsoftJsonOnlyConfiguration]
public class MyController { }

By default properties will be converted to camel case, but a specific casing format may be specified:

[NewtonsoftJsonOnlyConfiguration(TextCasing.KebabCase)]
public class MyController { }

and even the formatting:

[NewtonsoftJsonOnlyConfiguration(TextCasing.KebabCase, Formatting.Indented)]
public class MyController { }