JamesNK / Newtonsoft.Json

Json.NET is a popular high-performance JSON framework for .NET
https://www.newtonsoft.com/json
MIT License
10.71k stars 3.25k forks source link

Unable to Deserialize fields with prefirx "@" #2153

Open vikasNew opened 4 years ago

vikasNew commented 4 years ago

Hello,

i am facing a strange issue in Deserializing the json string to Model.

i hava a josn string which has some fields like "@timestamp". They has @ prefix.

when i deserialize them with "JsonConvert.DeserializeObject" then i could not get the json field value to my model. This is the issue with only fields which has @ prefix.

Source Code to Deserialize

 string responseJson = "{\"@timestamp\":\"2019-09-06T12:40:22.7305343+05:30\",\"level\":\"Information\",\"messageTemplate\":\"test message template\",\"message\":\"test message\"}";

            var deserializeResponse = JsonConvert.DeserializeObject<EntityModel>(responseJson, new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore,
                MissingMemberHandling = MissingMemberHandling.Ignore
            });

            Console.WriteLine(deserializeResponse.@timestamp.ToString());

Model

  public class EntityModel
  {
      public DateTime @timestamp { get; set; }
      public string level { get; set; }
      public string messageTemplate { get; set; }
      public string message { get; set; }
  }

Output

01/01/0001 00:00:00

Then how to get the right @timestamp value in model ?

Thanks in anticipation !!

bartelink commented 4 years ago

The @ in your code is being interpreted as a verbatim identifier indicator.

The best way to bind is likely to tag it with [JsonProperty("@timestamp")] (though the verbatim literal mechanism will also let you name it that way via something like: public DateTime @"@timestamp" {get;set;})

dovisutu commented 4 years ago

That's right, and this should only happen in c# since we use [...] as a verbatim identifier indicator in vbnet like:

Public [Next] As Dictionary(Of List(Of String), String)

It's not the question on Json.net, but by design in c#.

bartelink commented 4 years ago

@dovisutu int F#, you put double ticks around verbatim identifiers. e.g.

let [<Fact>] ``This is a test method`` () = Assert.Equal(1,1)

@vikasNew Can you close this please? (unless you have an open problem)