C
C#2y ago
ogie1985

❔ deserialize in csharp

is c# deserializer smart enough to deserialize the fields it only got or does your class have to match exactly the same ? Because I can sometimes get optional fields
8 Replies
ero
ero2y ago
Do you have any examples?
ogie1985
ogie1985OP2y ago
basically my json sometimes does not contain the fields my class got is it still able to deserialize with some help of some attritbutes i don't know or is it just no tpossible to deserialize
ero
ero2y ago
Then those fields' values will be their default So if you have a string in your class, but that string isn't in the json, that string's value will be null after deserialization
ogie1985
ogie1985OP2y ago
Yeah so I basically have a field which is a list of a class and that class contains a list of other classes but the base fields keep returning null because probably something inside that field of another class could not be matched?
MODiX
MODiX2y ago
Ero#1111
REPL Result: Success
var json = """
{
"Foo": "Bar",
"Baz": "Qux"
}
""";

var root = System.Text.Json.JsonSerializer.Deserialize<Root>(json);
Console.WriteLine(root.Baz);
Console.WriteLine(root.Quo is null);

class Root
{
public string Baz { get; set; }
public string Quo { get; set; }
}
var json = """
{
"Foo": "Bar",
"Baz": "Qux"
}
""";

var root = System.Text.Json.JsonSerializer.Deserialize<Root>(json);
Console.WriteLine(root.Baz);
Console.WriteLine(root.Quo is null);

class Root
{
public string Baz { get; set; }
public string Quo { get; set; }
}
Console Output
Qux
True
Qux
True
Compile: 656.307ms | Execution: 54.890ms | React with ❌ to remove this embed.
ero
ero2y ago
Hard to say without seeing all classes and the json
Angius
Angius2y ago
Also, (de)serialization in C# generally doesn't support fields, only properties
Accord
Accord2y 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