1

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.'

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.

David L
  • 32,885
  • 8
  • 62
  • 93
gougou4ga
  • 13
  • 2
  • Does this answer your question? [JsonConvert.DeserializeObject special characters Unterminated string. Expected delimiter:](https://stackoverflow.com/questions/21565404/jsonconvert-deserializeobject-special-characters-unterminated-string-expected-d) – Jose Nuno Dec 10 '21 at 17:48
  • $id is a special value to Newtonsoft, it's for object reference serialization. It will look for another object with the id "{ 0.1, 0.9 }" and doesn't like that value. – CodeCaster Dec 10 '21 at 17:53

1 Answers1

1

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

David L
  • 32,885
  • 8
  • 62
  • 93