5

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);
    }
  }
Vincent Mimoun-Prat
  • 28,208
  • 16
  • 81
  • 124

1 Answers1

4

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

David Neale
  • 16,498
  • 6
  • 59
  • 85
  • Thanks, that works. Would there be any mean to specify some custom way of parsing the JSON for some of the data members? – Vincent Mimoun-Prat Sep 08 '11 at 15:35
  • It depends what sort of control you need. I find that JSON.NET http://json.codeplex.com/ allows for more control that the datacontract one. You can create `JSONConverter`s. Otherwise, you can create surrogate classes to define how to serialize using the data contract one - http://msdn.microsoft.com/en-us/library/system.runtime.serialization.idatacontractsurrogate.aspx – David Neale Sep 08 '11 at 16:01