Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newtonsoft Json deserialize to dynamic list with boolean property turns into string

Tags:

json

c#

json.net

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?

like image 482
goroth Avatar asked Dec 07 '16 19:12

goroth


Video Answer


2 Answers

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.

like image 62
goroth Avatar answered Nov 14 '22 22:11

goroth


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.

like image 39
Christian Gollhardt Avatar answered Nov 14 '22 21:11

Christian Gollhardt