Search code examples
c#jsonpubnub

Deserialize raw JSON and convert to custom C# Object


I have the following raw JSON string:

[\"Hello World!\",\"94952923696694934\",\"MyChannel\"]

I have tried the following without luck:

My custom object class:

public class MyObject
{
   public string msg { get; set; }
   public string id { get; set; }
   public string chn { get; set; }
}

JSON string:

string str = "[\"Hello World!\",\"94952923696694934\",\"MyChannel\"]";

1st attempt at deserilization using System.Web.Script.Serialization:

JavaScriptSerializer serializer = new JavaScriptSerializer();
MyObject obj1 = serializer.Deserialize<MyObject>(str);

2nd attempt at deserilization using Newtonsoft.Json:

MyObject obj2 = JsonConvert.DeserializeObject<MyObject>(str);

Both attempts fail. Any suggestions?


Solution

  • You have a JSON array of strings, not an object with property names.

    So the best you can do here is to deserialize the array:

    IEnumerable<string> strings =
        JsonConvert.DeserializeObject<IEnumerable<string>>(str);
    

    ...then use the resulting sequence strings as you see fit.