小编典典

使用JavaScriptSerializer将实体映射到JSON

json

我的实体是这样的:

class Address
{
     public string Number { get; set; }
     public string Street { get; set; }
     public string City { get; set; }
     public string Country { get; set; }
}

class Person
{
     public string Name { get; set; }
     public int Age { get; set; }
     public Address PostalAddress { get; set; }
}

Person newPerson = 
    new Person()
    {
       Name = "Kushan",
       Age = 25,
       PostalAddress = 
           new Address()
           {
               Number = "No 25",
               Street = "Main Street",
               City = "Matale",
               Country = "Sri Lanka"
           }
    };

现在,我想将此newPerson对象映射到这样的JSON对象中,

{ 
     "PER_NAME" : "Kushan",
     "PER_AGE" : "25",
     "PER_ADDRESS" : {
                          "ADD_NUMBER" : "No 25",
                          "ADD_STREET" : "Main Street",
                          "ADD_CITY" : "Matale",
                          "ADD_COUNTRY" : "Sri Lanka"
                     }
}

注意:以上仅是示例。

我需要的是,我需要在序列化时自定义Key。默认情况下,它以属性名称为键。我无法更改属性名称。这该怎么做?

另外,是否可以更改JSON obj中出现的键/值对的顺序?


阅读 247

收藏
2020-07-27

共1个答案

小编典典

您需要将DataContract属性添加到您的类和DataMember属性。套装Name的属性DataMemeber到您的自定义属性名称和属性Order属性定义的顺序。

[DataContract]
public class Person
{
    [DataMember(Name = "PER_NAME", Order = 1)]
    public string Name { get; set; }

    [DataMember(Name = "PER_AGE", Order = 2)]
    public int Age { get; set; }

    [DataMember(Name = "PER_ADDRESS", Order = 3)]
    public Address PostalAddress { get; set; }
}

然后,您可以执行以下操作:

var newPerson = new Person()
{
    Name = "Kushan",
    Age = 25,
    PostalAddress = new Address()
    {
        Number = "No 25",
        Street = "Main Street",
        City = "Matale",
        Country = "Sri Lanka"
    }
};

MemoryStream stream = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person));
ser.WriteObject(stream, newPerson);

要检查结果:

var result = Encoding.ASCII.GetString(stream.ToArray());

{"PER_NAME":"Kushan","PER_AGE":25,"PER_ADDRESS":{"ADD_NUMBER":"No 25","ADD_STREET":"Main Street","ADD_CITY":"Matale","ADD_COUNTRY":"Sri Lanka"}}
2020-07-27