Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map entity to JSON using JavaScriptSerializer

My entities are like this:

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"
           }
    };

Now I wanna map this newPerson object into JSON object like this,

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

Note: Above is just an example.

What I need is, I need to customize the Key at the serializing time. by default it is taking property name as the key. I can't change property names. How to do this?

Also, is it possible to change to order of appearing key-value pairs in JSON obj.?

like image 679
Sency Avatar asked Jun 18 '11 18:06

Sency


2 Answers

You need to add DataContract attributes to your classes and DataMember to the properties. Set Name property of DataMemeber attribute to your custom property name and Order property to define the 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; }
}

Then you can do this:

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);

To check the result:

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"}}
like image 200
Alex Aza Avatar answered Oct 02 '22 07:10

Alex Aza


You can serialize an anonymous type with JavaScriptSerializer, so you might try projecting your object into the shape you want to serialize:

person.Select(s => new { PER_NAME = s.Name, PER_AGE = s.Age });
like image 28
gram Avatar answered Oct 02 '22 08:10

gram