skip to Main Content

I am deserializing two very simple JSON dictionaries:

{"name": "Premium"}

{"na/me": "Premium"}

The JSON path of the first entry in the first dictionary is "name" (as expected). However, the JSON path of the first entry in the second dictionary is "[‘na/me’]", but I would expect it to be "na/me". Can anyone explain what is happening?

Here is some code to help better understand:

string object1 = @"{""name"" : ""Premium""}";
var object1Deserialized = JsonConvert.DeserializeObject<Dictionary<string,string>>(object1);
var object1JToken = JToken.FromObject(object1Deserialized);
Assert.AreEqual("name", object1JToken.Children().First().Path);

string object2 = @"{""na/me"" : ""Premium""}";
var object2Deserialized = JsonConvert.DeserializeObject<Dictionary<string, string>>(object2);
var object2JToken = JToken.FromObject(object2Deserialized);
Assert.AreEqual("['na/me']", object2JToken.Children().First().Path);
//The above test case passes

For some reason, object2JToken.Children().First().Path is "['na/me']" rather than "na/me". Is this behavior intended? Or a bug?
Using .NET 7.0 and Newtonsoft.Json 13.0.2.

2

Answers


  1. Why you use Newtonsoft.Json while .NET 7 has a great built-in standard serializer !!

    using System.Text.Json;
    
    string object2 = @"{""na/me"" : ""Premium""}";
    var d = JsonSerializer.Deserialize<Dictionary<string, string>>(object2);
    
    Console.WriteLine(d.Keys.First());
    

    the output as you expect

    na/me
    
    Login or Signup to reply.
  2. Your code can’ t be even compilled and you have double lines that do the same. Try this

    string object2 = @"{""na/me"" : ""Premium""}";
    var object2JToken = JToken.Parse(object2);
     
    Assert.AreEqual("['na/me']", object2JToken.First().Path);
    
    //but maybe it is better
    
    Assert.AreEqual("na/me",JObject.Parse(object2).Properties().First().Name;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search