Newtonsoft Json deserialize for a dynamic list with a boolean property turns into a string

It is not possible to deserialize a dynamic list containing the boolean property into a logical one. 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 bound to a grid or other control, it considers this to be a "string", not a "logical" one.

Any suggestions?

+5
source share
4 answers

So, I tried installing LinqPad and finding out why it worked for vendettamit , but it did not work in my C # application.
Which led me to this article in How to reset JObject Newtonsoft in LinqPad .

Then I noticed that rdavisau used the following code.

 JsonConvert.DeserializeObject<ExpandoObject>(jsonString) 

But I used the following code.

 JsonConvert.DeserializeObject<List<dynamic>>(jsonString) 

So, as soon as I changed my code to the following. Everything worked correctly.

 JsonConvert.DeserializeObject<List<ExpandoObject>>(jsonString) 

ExpandoObject was the part I was missing.

+2
source

Since true in JSON is bool and "true" is a string , this seems like an error. To do this, I create a new problem on the error tracker .

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); 

It also has the advantage of conformance checking and better run-time performance.

+2
source

I just tried to replicate your code, as in LINQPAD, using JSON.NET 9.0.1 . I did not see a problem there:

enter image description here

0
source

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 probably due to the fact that JValue is forcibly inserted into the string during binding.

0
source

Source: https://habr.com/ru/post/1260944/


All Articles