Custom DataMember names to deserialize a JSON class

Vincent Mimoun-Prat picture Vincent Mimoun-Prat · Sep 8, 2011 · Viewed 9.4k times · Source

I cannot manage to specify custom names for properties. I receive some JSON from the server (which I cannot change) with some ugly property names. I'd like the C# code to stick to naming conventions.

Below is the code I have (result0.StringValue stays null):

  [TestClass()]
  public class WebServiceResultConverterTest
  {
    [DataContract(Name = "SimpleObject")]
    private class SimpleObject
    {
        [DataMember(Name = "str_value")]
        public String StringValue { get; set; }

        [DataMember(Name = "int_value")]
        public String IntValue { get; set; }
    }

    [TestMethod()]
    public void DeserializeTest()
    {
        String input0 = @"{
          ""str_value"": ""This is a test string"",
          ""int_value"": 1664
        }";

        JavaScriptSerializer serializer = new JavaScriptSerializer();
        SimpleObject result0 = serializer.Deserialize<SimpleObject>(input0);

        Assert.AreEqual("This is a test string", result0.StringValue);
        Assert.AreEqual(1664, result0.IntValue);
    }
  }

Answer

David Neale picture David Neale · Sep 8, 2011

You need to use the DataContractJsonSerializer with those attributes. I believe the JavascriptSerializer is now obsolete as of .Net 3.5.