C
C#2y ago
Indeed

❔ JsonDeserializer letting null for string type

Hi! I'm facing an issue where when deserializing json, the parser allows a null for string which breaks my app. Can i somehow specify that it is not to be null?
{"Location":{"CityName":null,"Latitude":0,"Longitude":0}}
{"Location":{"CityName":null,"Latitude":0,"Longitude":0}}
public class PersistentData {
public Location? Location { get; set; }
}

public class Location {
public string CityName { get; internal set; }
public double Latitude { get; internal set; }
public double Longitude { get; internal set; }
}
public class PersistentData {
public Location? Location { get; set; }
}

public class Location {
public string CityName { get; internal set; }
public double Latitude { get; internal set; }
public double Longitude { get; internal set; }
}
9 Replies
Indeed
IndeedOP2y ago
because i do have an error handling for deserialization that I'd like it to fall under but it's not throwing an exception
Anton
Anton2y ago
is nullability enabled? are you using System.Text.Json?
Indeed
IndeedOP2y ago
Yup! And as for nulability I did not see anywhere a setting for that and google showed no results
Anton
Anton2y ago
there's a property for msbuild called Nullable, you set it in the csproj file
Indeed
IndeedOP2y ago
Oh, pesimistic optimistic nullability thought you were talking about global System.Text.Json settings rn I have <Nullable>enable</Nullable> I assume i should do false?
cathei
cathei2y ago
Nullable reference type annotation should not change the meaning of code, I don’t think STJ has option for disallowing null. You probably need to use custom serialization contract or throw exception from constructor/property setter for null.
Indeed
IndeedOP2y ago
Oh, shame. I've tried such approach but seemed very verbose. Since it's more of a pet peeve than an actual appearing bug I guess I'll go without it. Thank you for your help ❤️
cathei
cathei2y ago
No problem, looks like the idea itself is exist as issue here https://github.com/dotnet/runtime/issues/1256 but not implemented
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