✅ JsonConvert.DeserializeObject return contains all null elements
Using
Newtonsoft.Json
, I have the following JSON (attached) with the following deserializer code:
However, the deserializer is not throwing an error but every element of DBFile
is null.
https://cdn.discordapp.com/attachments/1177777512525340752/1179410186717364324/image.png?ex=6579ae54&is=65673954&hm=c0ab82bfb39fd7785f407e64f07aaba100ba3cad3f1326bf4a59fb3b4a3935f4&24 Replies
that is the default behaviour, if u want to change that u will have to pass some settings:
https://www.newtonsoft.com/json/help/html/DeserializeMissingMemberHandling.htm
interesting
ah, I think I see what happens
good 'ol formatting and string escapes
not exactly sure how to approach that
thats actually the wrong thingy.
this configures what happens if the JSON has some property that is not mapped to the POCO
to set if it throws or sets to
null
, it seems u need a custom ContractResolver
:
https://stackoverflow.com/questions/57673787/how-to-throw-a-jsonserializationexception-when-a-property-is-missing-in-the-json#answer-57680436the issue moreso lies in the inability of it to properly parse the JSON due to string formatting
do u mean because the
\r\n
s in there?¯\_(ツ)_/¯
it can't find an obvious key that is clearly there, so something is blocking it from doing so
because they dont cause an issue, these are whitespaces (a windows line break to be exactly)
removed the \r\n formatting strings but it still fails
perhaps it's the
\"Timestamp\"
nope, thats just how visual studio displays the string
then I can't tell you what the issue is here
it can't find the key "Timestamp" even though it's there
aaah, i think i see the issue
its the typical property vs field thingy i guess
hm?
well, basically u have a bunch of private fields like
DBFile.Timestamp
, by default these are ignored
By default a type's properties are serialized in opt-out mode. What that means is that all public fields and properties with getters are automatically serialized to JSON, and fields and properties that shouldn't be serialized are opted-out by placing JsonIgnoreAttribute on them. To serialize private members, the JsonPropertyAttribute can be placed on private fields and properties.
The More You Know ™️
that would indeed do it
btw is there a specific reason u r newtonsoft.json over
System.Text.Json
?
since .net 7 the latter is the preferred library for thishard to teach an old dog new tricks I guess haha
well, u wouldve run into the same issue anyway xD
but if u do not have to deal with somewhat broken JSON or some other niche use case thats a deviation from the standard, STJ is the better option.
its part of the BCL, its more performant and supports source generated (de-)serialization
alrighty, thanks! appreciate the help
glad i could help o7
if the problem is now solved, please dont forget to $close the thread
Use the /close command to mark a forum thread as answered