JavaScriptSerializer - how to deserialize a property with a dash ("-") in it's name?

Lars picture Lars · Sep 21, 2011 · Viewed 8.2k times · Source

Trying to deserialize this JSON:

    {
        "result":"success"
        "arguments": {
            "activeTorrentCount":22,
             "cumulative-stats": {
                  "downloadedBytes":1111,
             }
         }
     }

My class:

        private class DeserializationMain
        {
            public string result; //works

            public args arguments; //works, has deserialized activeTorrentCount
            public class args
            {
                public int activeTorrentCount;

                public current cumulative_stats; //doesn't work, equals null
                public class current
                {
                    public long downloadedBytes;
                }
            }
        }

I guess cumulative-stats doesn't get deserialized because it has cumulative_stats variable name in my class, how to deserialize that thing with a dash?

Answer

Icarus picture Icarus · Sep 21, 2011

One alternative is to use the DataContractJsonSerializer instead of the JavascriptSerializer.

If you declare your classes like this:

        [DataContract]
        private class DeserializationMain
        {
            [DataMember(Name = "result")]
            public string result; //works
            [DataMember(Name = "arguments")]
            public args arguments; //works, has deserialized activeTorrentCount
            [DataContract]
            public class args
            {
                [DataMember(Name = "activeTorrentCount")]
                public int activeTorrentCount;

                [DataMember(Name = "cumulative-stats")]
                public current cumulative_stats; //doesn't work, equals null
                [DataContract]
                public class current
                {
                    [DataMember(Name = "downloadedBytes")]
                    public long downloadedBytes;
                }
            }
        }

You can deserialize it like this:

string json = "{\"result\":\"success\"   ,    \"arguments\": {  \"activeTorrentCount\":22,  \"cumulative-stats\": {   \"downloadedBytes\":1111      }       }     }";

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(DeserializationMain));
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
DeserializationMain result = serializer.ReadObject(ms) as DeserializationMain;

Console.WriteLine("Cumulative-stats.downloadedBytes: "+result.arguments.cumulative_stats.downloadedBytes); 

Will produce: Cumulative-stats.downloadedBytes: 1111