Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom DataMember names to deserialize a JSON class

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);
    }
  }
like image 328
Vincent Mimoun-Prat Avatar asked Oct 11 '22 01:10

Vincent Mimoun-Prat


1 Answers

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

like image 141
David Neale Avatar answered Oct 18 '22 05:10

David Neale