开发者

Custom DataMember names to deserialize a JSON class

开发者 https://www.devze.com 2023-04-04 01:25 出处:网络
I cannot manage to specify custom names for properties. I receive som开发者_运维百科e JSON from the server (which I cannot change) with some ugly property names. I\'d like the C# code to stick to nami

I cannot manage to specify custom names for properties. I receive som开发者_运维百科e 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);
    }
  }


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

0

精彩评论

暂无评论...
验证码 换一张
取 消