C
C#Mango

JsonSerializerOptions

To be continued
M
Mango45d ago
@maxmahem post here Taking it out of #chat
M
maxmahem45d ago
C#
builder.RegisterInstance(preConfiguredSerializationOptions).Keyed("Sprite");

public class SpriteDeserializaer([KeyFilter("Sprite")] JsonSerializationOptions options) { }
C#
builder.RegisterInstance(preConfiguredSerializationOptions).Keyed("Sprite");

public class SpriteDeserializaer([KeyFilter("Sprite")] JsonSerializationOptions options) { }
something like that. unless I'm misunderstanding you. Do you need to get multiple different options in the same class?
M
Mango45d ago
No, one instance of options per attribute But I would likely use one attribute per class Hold on, I’ll have to switch computers to make a non working demo
M
maxmahem45d ago
yeah, then something like the above should work. MS's thing uses a different syntax, but the principle is the same. The problem for me is I have a somewhat convoluted method for deserializing data back into these instances, which is tricky to do, and currently relies on inheritance, so this strategy would mess it up.
M
Mango45d ago
i dont see how it does
M
maxmahem45d ago
it's tangental to this, but I've got a whole scheme for loading data back in to like object instances from serialization... not hard to deserialize them of course, but STJ just produces a new object and I can't easily just have that object replace the current object in my IoC container, so I've got to copy the data over. And doing that currently relies on them all being sub-classes of a given type. I could probably switch over to them implementing an interface but, regardless of what I do, I can't have a JsonSerializationOption implement that interface, so there probably isn't any easy way to collect them with all my other options. anyways that's more a me problem, you aren't likely to want to do any of this 😛
M
Mango45d ago
this is what i mean:
public class WeatherForecast
{
public string CityName { get; set; }
public decimal Temperature { get; set; }
}

[AttributeUsage(AttributeTargets.Class)]
public class JsonSerializerOptionsAttribute : Attribute
{
public bool AllowTrailingCommas { get; set; }
// magic
}

[Route("api/v1/[controller]")]
[ApiController]
[JsonSerializerOptions(AllowTrailingCommas = true)] // <-- custom attribute applied to class but also designed to be able to be applied on methods too
public class LegacyController : ControllerBase
{
[Route("get")]
public ActionResult<WeatherForecast> HttpGetAttribute()
{
return Ok(new WeatherForecast());
// returns { cityName = "", temperature = 32.5, }
}
}

[Route("api/[controller]")]
[ApiController]
public class NewController : ControllerBase
{
[Route("get")]
public ActionResult<WeatherForecast> HttpGetAttribute()
{
return Ok(new WeatherForecast());
// returns { cityName = "", temperature = 32.5 }
}
}
public class WeatherForecast
{
public string CityName { get; set; }
public decimal Temperature { get; set; }
}

[AttributeUsage(AttributeTargets.Class)]
public class JsonSerializerOptionsAttribute : Attribute
{
public bool AllowTrailingCommas { get; set; }
// magic
}

[Route("api/v1/[controller]")]
[ApiController]
[JsonSerializerOptions(AllowTrailingCommas = true)] // <-- custom attribute applied to class but also designed to be able to be applied on methods too
public class LegacyController : ControllerBase
{
[Route("get")]
public ActionResult<WeatherForecast> HttpGetAttribute()
{
return Ok(new WeatherForecast());
// returns { cityName = "", temperature = 32.5, }
}
}

[Route("api/[controller]")]
[ApiController]
public class NewController : ControllerBase
{
[Route("get")]
public ActionResult<WeatherForecast> HttpGetAttribute()
{
return Ok(new WeatherForecast());
// returns { cityName = "", temperature = 32.5 }
}
}
if a class/method doesnt have that attribute, global serializer options are used. If it does have it, then the options from that attribute instance is used how would you use DI there?
M
maxmahem45d ago
ah, I see I see. well.. if you can't use constructor injection autofac at least can do property injection, though I don't know if you can use it along with keyed services.
M
Mango45d ago
well you can use DI in general but only if the attribute lets you
M
maxmahem45d ago
I think we may be talking cross purposes though. Is there some reason you can't use ctor injection? It feels like a better way to go instead of trying to resolve what you want manually via reflection.
M
Mango45d ago
so im still wondering how DI helps here what service do you use i can resolve any service i have registered in my controller no problem
M
maxmahem45d ago
but I mean you could do...
C#
public class LegacyController([KeyFilter("LegacyOptions") JsonSerializerOptions options)

public class NewController([KeyFilter("NewOptions"] JsonSerializerOptions options)
C#
public class LegacyController([KeyFilter("LegacyOptions") JsonSerializerOptions options)

public class NewController([KeyFilter("NewOptions"] JsonSerializerOptions options)
M
Mango45d ago
and do what with those services?
M
maxmahem45d ago
pass them to whatever needs the options?
M
Mango45d ago
i cant pass a service up to an attribute tho
M
maxmahem45d ago
I'm confused, is this not where they are needed? does LegcyController not perform serialization?
M
Mango45d ago
No, the framework does it after Ok() or the return in the method happens The controller itself does not do it
M
maxmahem45d ago
ahhh I see.
M
Mango45d ago
It CAN, but the framework does it
M
maxmahem45d ago
gotcha. Hmm, well I don't know how you can instruct the frameworks automagic to behave differently.
UU
Unknown User45d ago
M
maxmahem45d ago
yeah I was just going to suggest you can write your own custom converter it could probably be just a passthrough and add the necessary options to the Read and Write methods kind of messy though, but it would work.
UU
Unknown User45d ago
M
Mango45d ago
Is addjsonoption a method?
UU
Unknown User45d ago
M
maxmahem45d ago
C#
public class LegacyControlerJsonConverter : JsonConverter<LegacyController> {
public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) {
options.AllowTrailingCommas = true;
// I *think* this method and a matching read one exist.
reader.Deserialize<LegacyController>(options);
}

public override void Write(Utf8JsonWriter writer, LegacyController controller, JsonSerializerOptions options) {
options.AllowTrailingCommas = true;
// I *think* this method and a matching read one exist.
writer.Serialize<LegacyController>(options);
}
C#
public class LegacyControlerJsonConverter : JsonConverter<LegacyController> {
public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) {
options.AllowTrailingCommas = true;
// I *think* this method and a matching read one exist.
reader.Deserialize<LegacyController>(options);
}

public override void Write(Utf8JsonWriter writer, LegacyController controller, JsonSerializerOptions options) {
options.AllowTrailingCommas = true;
// I *think* this method and a matching read one exist.
writer.Serialize<LegacyController>(options);
}
UU
Unknown User45d ago
M
maxmahem45d ago
ngl I'm fairly lost t this point, lol.
M
Mango45d ago
Lol Wat? No I want to serialize the response Not the controller itself
UU
Unknown User45d ago
M
maxmahem45d ago
my b. I see it doesn't make sense now. I think I finally get it.
UU
Unknown User45d ago
M
Mango45d ago
I guess for both Yeah But I want to do it on a per controller or controller method basis Or maybe just controller
UU
Unknown User45d ago
M
Mango45d ago
Which is easily doable with the attribute usage
UU
Unknown User45d ago
M
Mango45d ago
Right, but I want the framework to do that Via an attribute I know that way is possible
UU
Unknown User45d ago
M
Mango45d ago
I want to use controller attribute decoration to drive it Is that possible?
UU
Unknown User45d ago
M
Mango45d ago
Because it’s easier than running serialization manually Code gold Golf
UU
Unknown User45d ago
M
Mango45d ago
Because that changes it on the type itself
UU
Unknown User45d ago
M
Mango45d ago
What do you mean a dot with JsonPropertyName?
UU
Unknown User45d ago
M
Mango45d ago
And that sets it no matter how many endpoints I have that returns or deserializes that?
UU
Unknown User45d ago
M
Mango45d ago
That isn’t what I want
UU
Unknown User45d ago
M
Mango45d ago
That’s not what I want
UU
Unknown User45d ago
M
Mango45d ago
I get that
UU
Unknown User45d ago
M
Mango45d ago
Ok, so is it doable with .Net? The attribute method I demoed above If not, then that’s fine
UU
Unknown User45d ago
M
Mango45d ago
I see
UU
Unknown User45d ago
M
Mango45d ago
Makes sense
UU
Unknown User45d ago
M
Mango45d ago
Ok How can I not do it that way and do it the way I want to try? If it’s possible That’s clearly the best way
UU
Unknown User45d ago
M
Mango45d ago
I want to know another way
UU
Unknown User45d ago
M
Mango45d ago
I meant the way you gave examples of
UU
Unknown User45d ago
M
Mango45d ago
They way you showed is the best way to handle different prop names with api versioning
UU
Unknown User45d ago
M
Mango45d ago
I see
UU
Unknown User45d ago
M
Mango45d ago
So I’ll keep on searching then
UU
Unknown User45d ago
M
Mango45d ago
Yes because I want to do something specific That isn’t being solved by your suggestions I would recommend looking at my code at the very beginning of this thread
Want results from more Discord servers?
Add your server
More Posts
C# Dictionary questionHi, if i have a dictionary in C# defined like so: `Dictionary<string, List<int>> test;` and I do `Li✅ Avalonia not showing rows in datagridThere are no rows in my datagrid in Avalonia, the headers are visible. I've checked if my list is emInfinite loop```c# /// ------------------------------------------------------------ /// <summary> /// Creates a sHow to connect my c# backend with the frontend?Hello, I created a ASP NET Core Web Api project with the command dotnet new webapi -minimal. In my ✅ Using `Func<ReadOnlySpan<char>,bool>` but not allowed due to Pointer TypeI am building a parser, and performance is of concern. So instead of allocating infinite strings wheconcurrency and atomicity Asp.net core web api and efcorelet's say there's an endpoint called AssingUser() ,this endpoint assigns one donation to this currenBuilding a generic repository for mongodbhello folks I was thinking build a generic repository structure for mongodb. but someday if i want Reading large xml file from archive by using XmlReader in Parallel modeHello 👋. I am looking for how can I read data from archive xml file in Parallel mode. I have archiResizing the Console window - Console ApplicationHi there, I'm trying to resize the console window in a Console Application. I have tried multiple ✅ Creating a datetime with a timezoneHow do I create a `DateTime` with `new DateTime(2010, 05, 12);` and give it a specific `TimeZoneInfoCustom Newtonsoft JSON deserializationI have a dictionary where: - The key will always be a string - The value will be either: - string Issue with Form.Close() in WinformsI have a custom form called CustomMessageBox In that form, I have a method that defines a button clIssue with IMGUI.Net.Hello, I am creating an ImGUI application and It doesn't let me move the ui across my entire screen,Issue with deserializing Enums in saved JSONHey, I've been trying to deserialize a list of cards I serialized in C#, the issue I'm having is it From HttpClient, can I save/copy the request to share with someone?Is there a way to copy raw request details? For example, I'm looking for a similar output like: -3D Unity RaycastingHi guys, currently working on a puzzle game involving lasers and mirrors, however, have hit a brick Computer Science - Computer ArchitectureOn a 64 bit system (where the bus length and word size are 64 bits) how would we determine the ammouConnecting SQLite in MAUIHow to connect the database without absolute path? If with it, the program works only on the computeDifferent HttpClient headersWhen I make an HTTP request in my browser (Chrome), I get different response headers than I do in myHttpRequestException:An error occurred while sending the request. WebExceptionHttpRequestException:An error occurred while sending the request. WebException:Unable to connect to