C
C#9mo ago
illy

❔ Deserializing JSON

I'm working on a project where I need to deserialize a JSON api response, and do things with the data. This is a little demo thing:
class Response {
[JsonProperty("success")]
[DefaultValue(false)]
public bool Success { get; private set; }

[JsonProperty("days")]
public Days Days { get; private set; }
}

class Days {
[JsonProperty("first_day")]
[DefaultValue("monday")]
public string FirstDay { get; private set; }
}
class Response {
[JsonProperty("success")]
[DefaultValue(false)]
public bool Success { get; private set; }

[JsonProperty("days")]
public Days Days { get; private set; }
}

class Days {
[JsonProperty("first_day")]
[DefaultValue("monday")]
public string FirstDay { get; private set; }
}
My issue is, I need to be able to use Response.Days.FirstDay, when my JSON response looks like this: {'success': true, 'first_night': 'friday'} Essentially, I want the DefaultValue to be present, even if the JSON doesn't contain the 'first_day' key. I'm really not sure how to do this, because I'd need to do this with dozens of attributes in about 6 subclasses, so doing it all manually would take ages and doesn't seem good for maintainability. Any help on how I can achieve this result? To get everything to 'exist' even if it doesn't exist in the JSON, just by using the default value?
6 Replies
Angius
Angius9mo ago
Well, you can have the optional property be nullable Then, whenever you access it, simply provide a fallback object.MaybeNull ?? 0
Pobiega
Pobiega9mo ago
What about using [JsonConstructor] to set the defaults?
Angius
Angius9mo ago
Or that, yeah
illy
illy9mo ago
How can I use that?
Pobiega
Pobiega9mo ago
public static class Program
{
public static void Run()
{
var options = new JsonSerializerOptions(JsonSerializerDefaults.Web)
{
WriteIndented = true
};

var json =
"""
{
"success": true,
"days": {
"first_night": "friday"
}
}
""";

var deser = JsonSerializer.Deserialize<Root>(json, options);
var jsonAgain = JsonSerializer.Serialize(deser, options);
Console.WriteLine(jsonAgain);
}
}

public class Root
{
public bool Success { get; set; } = false;
public Days Days { get; set; }
}

public class Days
{
[JsonPropertyName("first_day")] public string FirstDay { get; set; } = "monday";
}
public static class Program
{
public static void Run()
{
var options = new JsonSerializerOptions(JsonSerializerDefaults.Web)
{
WriteIndented = true
};

var json =
"""
{
"success": true,
"days": {
"first_night": "friday"
}
}
""";

var deser = JsonSerializer.Deserialize<Root>(json, options);
var jsonAgain = JsonSerializer.Serialize(deser, options);
Console.WriteLine(jsonAgain);
}
}

public class Root
{
public bool Success { get; set; } = false;
public Days Days { get; set; }
}

public class Days
{
[JsonPropertyName("first_day")] public string FirstDay { get; set; } = "monday";
}
I decided to use properties with default values instead of a constructor this outputs
{
"success": true,
"days": {
"first_day": "monday"
}
}
{
"success": true,
"days": {
"first_day": "monday"
}
}
Accord
Accord9mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server
More Posts
✅ In a WPF application, how do you keep a modal window above all other windows for that app?I only want that window on top of other windows for that application, not on top of everything.✅ Reoccurring times with a possibility to a one time rep in C#Suppose we have an entity which represents irl event, this event can reoccur every week or be one-ti❔ Property vs field?Hi everyone, I have a really basic but also really important question regarding C#. I have been cod❔ [EFCore] What is the right approach to generate hierarchy id for new child entity?I Use SQLServer & EF Core. been struggling to find the right approach to generate new h-id for new ✅ ConstructorsIf Constructors are just a method called when a class is created, how does the new operator in combi❔ Conditional in semantic kernel (skprompt.txt file)Hey guys, I currently using semantic kernel to do stuff related with AI in my console app. In sema❔ Can I/How would I do these things with CefGlue.Avalonia?So im trying to make something, but idk what to do because im not sure how much of this can even be ❔ how can i save flow layout panelim doing a simple video game library with C# but the problem is i cant save them when i add new pane❔ Is it possible to log for the user (not dev) with localization?Given that a multi-lingual app exists And it is currently configured to some language When somethingHow to sort a list of a class by property using LINQ when the name of the property comes from inputSo, im learning c# and im trying to solve an exercise. The issue im facing is, i have a class that h