goroth
goroth

Reputation: 2610

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

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?

Upvotes: 7

Views: 17042

Answers (4)

dviljoen
dviljoen

Reputation: 1632

I just ran:


string s = "[{ \"Field1\": 1, \"Field2\": \"Test 1\", \"Field3\": true }, { \"Field1\": 2, \"Field2\": \"Test 2\", \"Field3\": false }   ]";
var result = JsonConvert.DeserializeObject>(s);
Console.WriteLine("Type: {0}", result[0].Field3.Type);

and it gave me: Type: Boolean

The problem is likely because the JValue is being coerced into a string during the bind.

Upvotes: 0

goroth
goroth

Reputation: 2610

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.

Upvotes: 8

vendettamit
vendettamit

Reputation: 14687

I just tried replicating your code as is in LINQPAD with JSON.NET 9.0.1. I didn't see the issue there:

enter image description here

Upvotes: 0

Christian Gollhardt
Christian Gollhardt

Reputation: 17024

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.

Upvotes: 3

Related Questions