Can't seem to deserialize a dynamic list that contains a boolean property back into a boolean.
I have the following json.
[
{
"Field1": 1,
"Field2": "Test 1",
"Field3": true
},
{
"Field1": 2,
"Field2": "Test 2",
"Field3": false
}
]
When I use:
Newtonsoft.Json.JsonConvert.DeserializeObject<List<dynamic>>(jsonString)
I get Field3 = "True" or "False"
When binding to a grid or other control, it thinks this is a "string" and not a "boolean".
Any suggestions?
So I tried to install LinqPad and figure out why it was working for vendettamit yet it was not working in my C# application.
Which led me to this article on How to Dump a Newtonsoft JObject in LinqPad.
I then noticed that rdavisau used the following code.
JsonConvert.DeserializeObject<ExpandoObject>(jsonString)
Yet I was using the following code.
JsonConvert.DeserializeObject<List<dynamic>>(jsonString)
So once I changed my code to the following. It all worked correctly.
JsonConvert.DeserializeObject<List<ExpandoObject>>(jsonString)
ExpandoObject was the piece I was missing.
Since in JSON the value true
is bool and "true"
is string, it seems like a bug. I would create a new issue on their issue tracker for this.
A workaround would be to create a strong typed model for it.
public class FieldData
{
public int Field1 {get; set;}
public string Field2 {get; set;}
public bool Field3 {get; set;}
}
JsonConvert.DeserializeObject<List<FieldData>>(jsonString);
This has also the advantage of compiletime check and better runtime performance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With