简体   繁体   中英

Json array Deserialization Issue in C#

I have a Web API method to mapping a Json array to C# object.

My parameter should be like the following:

[{"event":"inbound","msg":"TestMEssage","ts":123456}]

and my code is

var events = JsonConvert.DeserializeObject<IEnumerable<MailEvent>>(mandrill_inbound);
public class MailEvent
    {

        [JsonProperty(PropertyName = "event")]
        public string Event { get; set; }

        [JsonProperty(PropertyName = "msg")]
        public string Msg { get; set; }

        [JsonProperty(PropertyName = "ts")]
        public string TimeStamp { get; set; }
    }

But when am trying to Deserialize the JSON it's showing exception.

But If I am trying to set a variable inside the method like

Public const string mandrill_inbound = @"[
    {
        ""event"": ""inbound"",
        ""msg"": ""tewst"",
        ""ts"": 1368214102
    },
    {
        ""event"": ""inbound"",
        ""msg"": ""test2"",
        ""ts"": 1368214102
    }
]";

This code will be working perfectly for me.

Noting that it has starting with @"" and all the key values are surrounded with multiple Double quotes( ""event"" ).

Actually what is the difference between these two formats.

Any help will be appreciated.

This is literally the same string without needing to escape anything.

That is the @ indicates that the string is declared as is, ignoring any and all characters that in a normal string would indicate some escape.

The only exception is the double arrow Quote. The double quote needs to be escaped when the string is prefixed by @. The way to do this, is by using ""

So the same string without @ would be

Public const string mandrill_inbound = "[\n" +
"{\n" +
    "\"event\": \"inbound\",\n" +
    "\"msg\": \"tewst\",\n" +
    "\"ts\": 1368214102\n" +
"},\n" +
"{\n" +
    "\"event\": \"inbound\",\n" +
    "\"msg\": \"test2\",\n" +
    "\"ts\": 1368214102\n" +
"}]";

The string above should also work. What is the exception you are getting?

Finally, I found the Issue,

It appears that the JSON I receive has been serialized twice, No idea from where this happened.The first double-quote might be added by your debugger, but the second (the escaped \\" one) really appears to be part of the data you're processing. The error message also makes sense this way, it deserializes a string and then attempts to cast it to an ApiResult.

"\"{\\"event\\":\\"Inbound\\",\\"msg\\":...

Try deserializing the data as a string and then deserializing its result to an ApiResult

   var content = response.Content;              
   var jsonResult = JsonConvert.DeserializeObject(content).ToString();
   var result= JsonConvert.DeserializeObject<Model>(jsonResult);

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