How to make DTO property optional for json schema - c#

I have a DTO that has a property that is relevant only to the GET response.
In the POST request I don't need it - more than this - I should not include it in the serialized json.
So, I get this DTO as a response for the GET request and send it (without the mentioned property) in the Body when making a POST request.
Except for removing the optional property from the original class and locate it in a an inherited class - what other options do I have ? (using the JsonProperties, for example or other options)
This is my DTO:
public class MyDTO
{
[JsonProperty("id")]
public int ID {get; set;}
[JsonProperty("remark")]
public string Remark {get; set;}
[JsonProperty("optionalremark")] //relevant only to the GET request
public string OptionalRemark {get; set;}
}

There are several ways how you achieve that:
Separate object
The most obvious choice could be to separate GET's response object from POST's request object. Most probably the two API can evolve independently. If any of these two changes then it requires modification on the DTO. You can use some sort of mapper (like AutoMapper) to define relationship between these two classes.
Conditional Serialization
Newtonsoft does support conditional seralization. All you have to do is to define a method which returns a bool and is named like ShouldSerialize{PropertyName}:
public class MyDTO
{
[JsonProperty("id")]
public int ID {get; set;}
[JsonProperty("remark")]
public string Remark {get; set;}
[JsonProperty("optionalremark")]
public string OptionalRemark {get; set;}
public bool ShouldSerializeOptionalRemark() => false;
}
This method is called only during serialization. So, deserialization works as expected.
ContractResolver
If you don't want to include a ShouldSerialize{PropertyName} method into your DTO then you can place this logic inside a custom ContractResolver:
public class MyDTOContractResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
if (property.DeclaringType == typeof(MyDTO) && property.PropertyName == nameof(MyDTO.OptionalRemark).ToLower())
{
property.ShouldSerialize = _ => false;
}
return property;
}
}
You can specify this resolver for SerializeObject and DeserializeObject as well:
var getResponse = JsonConvert.DeserializeObject<MyDTO>(json, new JsonSerializerSettings { ContractResolver = new MyDTOContractResolver() });
var postRequest = JsonConvert.SerializeObject(getResponse, new JsonSerializerSettings { ContractResolver = new MyDTOContractResolver() });
During deserialization it does not have any affect. So, if you need to you can register this resolver globally as well:
services.AddControllers()
.AddNewtonsoftJson(opts =>
{
opts.SerializerSettings.ContractResolver = new MyDTOContractResolver();
});
This code works in ASP.NET Core 3.x or higher projects. In case of older ASP.NET Core project, please use AddJsonOptions instead of AddNewtonsoftJson.

In this case, You can use [JsonIgnore] attribute on you DTO property, like this:-
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public List<SomethingDTO> something_dto { get; set; }

Related

JsonMediaTypeFormatter not formatting data correclty

I am using following code in ASP.NET Web API application.
//Support camel casing
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().FirstOrDefault();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
When returning JSON via POCO or DataTable, it converts property name in camel casing.
Assume My class has two properties.
Class Obj{
public string DataBase{ get; set; }
public string ChangedBy { get; set; }
}
When I return any object of this class, I will get JSON like this:
{
"dataBase":"Oracle",
"changedBy":"XYZ"
}
It seems issue is when you have '_' in the property name. CamelCasing is not making sense.
My class has columns like this:
DATA_BASE
CHANGED_BY
Now, I am receiving JSON like this:
{
"datA_BASE":"Oracle",
"changeD_BY":"XYZ"
}
I was expecting:
{
"dATA_BASE":"Oracle",
"cHANGED_BY":"XYZ"
}

Avoid allowing any case for property names in .NET core rest controller

I am creating a REST controller with .NET core 2.1 using [ApiController] and [FromBody]. Suppose my parameter object is:
public class CreateUserParmeters
{
public string Name {get; set;}
}
The JSON I can send can be:
{ "name":"Test" }
But also:
{ "Name":"Test" }
Or even:
{ "NaMe":"Test" }
This will all work fine. I would like to avoid this, and only allow name (so camelCase). Is there a way to enforce this?
Maybe this setting will help:
services.AddMvc().AddJsonOptions(opt =>
{
opt.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
Have you tried this?
I think you should investigate the following contract resolver.
In your Global.asax:
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
You could simply define the required json attribute name using the JsonProperty attribute on the model properties. It will serialise as you require, although it's not actually case sensitive when de-serialising json back to a model instance.
[JsonProperty("name")]
public string Name { get; set; }

JSON.NET Case Insensitive Deserialization not working

I need to deserialize some JSON into my object where the casing of the JSON is unknown/inconsistent. JSON.NET is supposed to be case insensitive but it not working for me.
My class definition:
public class MyRootNode
{
public string Action {get;set;}
public MyData Data {get;set;}
}
public class MyData
{
public string Name {get;set;}
}
The JSON I receive has Action & Data in lowercase and has the correct casing for MyRootNode.
I'm using this to deserialize:
MyRootNode ResponseObject = JsonConvert.DeserializeObject<MyRootnode>(JsonString);
It returns to be an initialised MyRootNode but the Action and Data properties are null.
Any ideas?
EDIT: Added JSON
{
"MyRootNode":{
"action":"PACT",
"myData":{
"name":"jimmy"
}
}
}
This is the .NET Core built-in JSON library.
I found another way of doing it.. just in case, somebody is still looking for a cleaner way of doing it. Assume there exists a Movie class
using System.Text.Json;
.
.
.
var movies = await JsonSerializer.DeserializeAsync
<IEnumerable<Movie>>(responseStream,
new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
Startup Options:
You can also configure at the time of application startup using the below extension method.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.AddJsonOptions(
x =>
{
x.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
});
}
Simply add JsonProperty attribute and set jsonProperty name
public class MyRootNode
{
[JsonProperty(PropertyName = "action")]
public string Action {get;set;}
[JsonProperty(PropertyName = "myData")]
public MyData Data {get;set;}
}
public class MyData
{
[JsonProperty(PropertyName = "name")]
public string Name {get;set;}
}
UPD: and yes, add some base type as #mjwills suggest
You need to add an additional class:
public class MyRootNodeWrapper
{
public MyRootNode MyRootNode {get;set;}
}
and then use:
MyRootNodeWrapperResponseObject = JsonConvert.DeserializeObject<MyRootNodeWrapper>(JsonString);
https://stackoverflow.com/a/45384366/34092 may be worth a read. It is basically the same scenario.
Also, change:
public MyData Data {get;set;}
to:
public MyData MyData {get;set;}
as per advice from #demo and #Guy .

ASP.NET Swagger IEnumerable<T>

In Swagger UI I get a model like:
Inline Model [
Inline Model 1
]
Inline Model 1 {
Id (string, optional),
ConnectionString (string, optional),
ConnectionState (string, optional)
}
for a REST Get method like:
public IEnumerable<Device> Get()
{
return new List<Device>();
}
Why is it not displayed correctly?
Adding Swagger Config from comments
public class SwaggerConfig
{
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration .EnableSwagger(c => { c.SingleApiVersion("v1", "api"); }) .EnableSwaggerUi(c => { });
}
}
public class Device
{
public string Id { get; set; }
public string ConnectionString { get; set; }
public string ConnectionState { get; set; }
}
In C# Asp.Net web api, I did this:
1- In SwaggerConfig.cs
.EnableSwagger(c =>
{//add this line
c.SchemaFilter<ApplyModelNameFilter>();
}
2- add a class that implements ISchemaFilter:
class ApplyModelNameFilter : ISchemaFilter
{
public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
{
schema.title = type.Name;
}
}
I got the idea from here
It seems like Swagger and/or NSwag do not handle Generic List/IList/IEnumerable types very well as a base type, perhaps because some frameworks that may try to connect with Swagger don't understand them.
I have worked around this by wrapping my List in another object. So, in your case, you may need to do something like:
public ListResponseObject<T>()
{
public IEnumerable<T> ResponseList {get; set;}
}
And then return from your controller like this:
public ListResponseObject<Device> Get()
{
return new ListResponseObject<Device>{ResponseList = new List<Device>()};
}
Not as simple... but should get it through Swagger better.
We've leveraged this to our advantage. We've applied this technique to all controllers (or something similar) so we have a more standardized response. We can also do this:
public ListResponseObject<T>() : ResponseObject<T>
{
public IEnumerable<T> ResponseList {get; set;}
}
public ResponseObject<T>()
{
public string Message {get; set;}
public string Status {get; set;}
}
And now you have a container that will make downstream handling a little easier.
Not an exact answer, but a work-around that's worked for us. YMMV
UPDATE: Here's a response to a question I posted in the NSwag GitHub issues:
I think its correct as is. Currently swagger and json schema do not support generics (only for arrays) and thus all generic types are expanded to non-generic/specific types... altough the models should be correct but you may end up with lots of classes...
An enhancement for supporting generics is planned but this will be not compliant with swagger and only work with nswag... (No support in swagger ui)

Using Serializable attribute on Model in WebAPI

I have the following scenario: I am using WebAPI and returning JSON results to the consumer based on a model. I now have the additional requirement to serialize the models to base64 to be able to persist them in cache and/or use them for auditing purposes. Problem is that when I add the [Serializable] attribute to the model so for converting the the model to Base64, the JSON output changes as follows:
The Model:
[Serializable]
public class ResortModel
{
public int ResortKey { get; set; }
public string ResortName { get; set; }
}
Without the [Serializable] attribute the JSON output is:
{
"ResortKey": 1,
"ResortName": "Resort A"
}
With the [Serializable] attribute the JSON output is:
{
"<ResortKey>k__BackingField": 1,
"<ResortName>k__BackingField": "Resort A"
}
How would I be able to use the [Serializable] attribute without changing the output of the JSON?
By default, Json.NET ignores the Serializable attribute. However, according to a comment to this answer by Maggie Ying (quoted below because comments are not meant to last), WebAPI overrides that behavior, which causes your output.
Json.NET serializer by default set the IgnoreSerializableAttribute to true. In WebAPI, we set that to false. The reason why you hit this issue is because Json.NET ignores properties: "Json.NET now detects types that have the SerializableAttribute and serializes all the fields on that type, both public and private, and ignores the properties" (quoted from james.newtonking.com/archive/2012/04/11/…)
A simple example that demonstrates the same behavior without WebAPI can look like this:
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
namespace Scratch
{
[Serializable]
class Foo
{
public string Bar { get; set; }
}
class Program
{
static void Main()
{
var foo = new Foo() { Bar = "Blah" };
Console.WriteLine(JsonConvert.SerializeObject(foo, new JsonSerializerSettings()
{
ContractResolver = new DefaultContractResolver()
{
IgnoreSerializableAttribute = false
}
}));
}
}
}
There are several ways around this behavior. One is to decorate your model with a plain JsonObject attribute:
[Serializable]
[JsonObject]
class Foo
{
public string Bar { get; set; }
}
Another way is to override the default settings in your Application_Start(). According to this answer, the default settings should do it:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = new Newtonsoft.Json.JsonSerializerSettings();
If that doesn't work, you could be explicit about it:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings()
{
ContractResolver = new DefaultContractResolver()
{
IgnoreSerializableAttribute = true
}
};

Categories