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