简体   繁体   中英

JsonConvert fails to deserialize a dictionary, when there are dots inside a key (of a key-value pair)

I'll present the issue with an example:

Let var st1 = "{\"AB\":true}"; var st2 = "{'A.B':true}" var st1 = "{\"AB\":true}"; var st2 = "{'A.B':true}" (difference is ' against " ).

This line fails: JsonConvert.DeserializeObject<Dictionary<string, bool>>(st1) (call stack below).

This line works as expected: JsonConvert.DeserializeObject<Dictionary<string, bool>(st2) .

If AB didn't have a dot (just AB for instance), both would work.

I found alternatives to JsonConvert that can deal with it, but I must use JsonConvert unfortunately (not my decision). Is there any way to overcome that with JsonConvert ?

Call stack from before:

Invalid JavaScript property identifier character: .. Path '', line 1, position 6.
Newtonsoft.Json.JsonReaderException: Invalid JavaScript property identifier character: .. Path '', line 1, position 6.
   at Newtonsoft.Json.JsonTextReader.ReadUnquotedPropertyReportIfDone(Char currentChar, Int32 initialPosition)
   at Newtonsoft.Json.JsonTextReader.ParseUnquotedProperty()
   at Newtonsoft.Json.JsonTextReader.ParseProperty()
   at Newtonsoft.Json.JsonReader.ReadAndAssert()
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
   at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
   at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
   at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)

JsonConvert can handle dots in strings:

    var st1 = "{ \"A.B\": true }";        
    var result = JsonConvert.DeserializeObject<Dictionary<string, bool>>(st1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM