Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JsonConvert.DeserializeObject throws an Error after using the result from JsonConvert.SerializeObject

When I use Newtonsoft.Json in C#, I find a problem like this

var dataDict = new Dictionary<string, List<double>>();

dataDict["$id"] = new List<double>() { 0.1, 0.9 };

var jsonStr = JsonConvert.SerializeObject(dataDict);

var back = JsonConvert.DeserializeObject<Dictionary<string, List<double>>>(jsonStr);

Then it throws error

Newtonsoft.Json.JsonSerializationException: ‘Unexpected token when
deserializing object: Float. Path ‘$id[0]’, line 1, position 11.’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If I remove the charater "$", it works.

I acknowledge "$" is a speical token, my question: if you can SerializeObject, why you can not DeserializeObject?

Any work around here? Any advice is welcome! Thanks.

>Solution :

You can configure Json.NET to ignore metadata properties (properties prefaced by ‘$’) by passing JsonSerializerSettings to your deserialize operation.

var back = JsonConvert.DeserializeObject<Dictionary<string, List<double>>>(
    jsonStr,
    new JsonSerializerSettings 
    { 
        MetadataPropertyHandling = MetadataPropertyHandling.Ignore 
    });

This correctly deserializes into your target dictionary structure:

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading