Serialize only specific class properties to JSON string using JavaScriptSerializer

About one year ago I wrote a blog post about JavaScriptSerializer and the Serialize and Deserialize methods it supports.

Note: This blog post has been in draft for sometime now, so I decided to complete it and publish it.

There might be situation when you want to serialize to JSON string only specific properties of a given class. You can do that using JavaScriptSerializer in combination with LINQ.

Let’s say we have the following class definition

public class Customer
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public string Email { get; set; }
    public int Age { get; set; }
    public bool Drinker { get; set; }
    public bool Smoker { get; set; }
    public bool Single { get; set; }
}

Next, lets create method that will create sample data for our demo

private List<Customer> GetListOfCustomers()
{
    List<Customer> customers = new List<Customer>();
    customers.Add(new Customer()
    {
        Name = "Hajan",
        Surname = "Selmani",
        Age = 25,
        Drinker = false,
        Smoker = false,
        Single = false,
        Email = "hajan@hajan.com"
    });
    customers.Add(new Customer()
    {
        Name = "John",
        Surname = "Doe",
        Age = 29,
        Drinker = false,
        Smoker = true,
        Single = false,
        Email = "john@doe.com"
    });
    customers.Add(new Customer()
    {
        Name = "Mark",
        Surname = "Moris",
        Age = 34,
        Drinker = true,
        Smoker = true,
        Single = true,
        Email = "mark@moris.com"
    });

    return customers;
}


So, we have three customers with some property values for each of them. Now, lets serialize some of their properties using JavaScriptSerializer.

First, you must put the following directive:

using System.Web.Script.Serialization;
Next, we create list of customers that will get the returned value from GetListOfCustomers method and we create instance of JavaScriptSerializer class
List<Customer> customers = GetListOfCustomers();
JavaScriptSerializer serializer = new JavaScriptSerializer();

Now, lets say we want to serialize as JSON string and retrieve only the Age property data… We do that with only one simple line of code:

//this will serialize only the 'Age' property
string jsonString = serializer.Serialize(customers.Select(x => x.Age));

The result will be:

Nice!

Now, what if we want to serialize multiple properties at once, but not all class properties?

string jsonStringMultiple = serializer.Serialize(customers.Select(x => new { x.Name, x.Surname, x.Age }));

The result will be:

You see, the result is an array of objects with the four properties and their corresponding values we have selected using the LINQ query above. You can see that integer and boolean values are without quotes, which is correct way of serialization.

Now, you probably saw a difference somewhere? Namely, in the first example where we have selected only one property, there are only the values of the property (no property name), while in the second example we have the property name and it’s corresponding value… Why is it like that? It’s because in the second query, we use new { … } to specify multiple properties in the select statement. Therefore, the anonymous new { … } creates an object of each found item. So, if you are interested to make some more tests, run the following two lines of code:

var customers1 = customers.Select(x => x.Name).ToList();
var customers2 = customers.Select(x=> new { x.Name } ).ToList();

and you will obviously see the difference.

If we use the new { } way for single property selection, like in the following example

string jsonString2 = serializer.Serialize(customers.Select(x => new { x.Age }));


the result will be:


The complete demo code used for this blog post:

List<Customer> customers = GetListOfCustomers();
JavaScriptSerializer serializer = new JavaScriptSerializer();

//this will serialize only the 'Age' property
string jsonString = serializer.Serialize(customers.Select(x => x.Age ));

string jsonStringMultiple = serializer.Serialize(customers.Select(x => new { x.Name, x.Surname, x.Age, x.Drinker }));

var customers1 = customers.Select(x => x.Name).ToList();
var customers2 = customers.Select(x=> new { x.Name } ).ToList();

string jsonString2 = serializer.Serialize(customers.Select(x => new { x.Age }));

You can download the demo project here.

I hope this was useful blog post.

Regards,
Hajan

Published Wednesday, August 10, 2011 1:27 AM by hajan

Comments

# re: Serialize only specific class properties to JSON string using JavaScriptSerializer

Wednesday, August 10, 2011 6:31 AM by Vest

Thank you for the article.

But, I am afraid this approach should not work for DateTime values, because they cannot be serialized to JSON format. What will you recommend when dealing with date values?

They can have one time zone on the client side, but a different time zone on the server side. Should they be used in the UTC format

# re: Serialize only specific class properties to JSON string using JavaScriptSerializer

Wednesday, August 10, 2011 7:37 AM by hajan

Vest, why do you think DateTime values cannot be serialized to JSON format?

1. Add new property to the Customer class from the demo:

public DateTime BirthDate { get; set; }

2. Add some values in the sample data (ex: BirthDay = new DateTime(1985, 11, 05))

3. Do the following

string jsonDateString = serializer.Serialize(customers.Select(x => new { x.BirthDate }));

The result should be:

[{"BirthDate":"\/Date(499993200000)\/"},{"BirthDate":"\/Date(359848800000)\/"},{"BirthDate":"\/Date(227487600000)\/"}]

For the following dates in Customer list:

- BirthDate = new DateTime(1985, 11, 05)

- BirthDate = new DateTime(1981, 05, 28)

- BirthDate = new DateTime(1977, 03, 18)

Now, copy paste the result values and run this JavaScript (the values are copied in the code snippet)

   <script type="text/javascript">

       var jsonString = [{ "BirthDate": "\/Date(499993200000)\/" }, { "BirthDate": "\/Date(359848800000)\/" }, { "BirthDate": "\/Date(227487600000)\/"}];

       for (i in jsonString) {

           //alert(jsonString[i]["BirthDate"]);

           var jsonDate = jsonString[i]["BirthDate"];

           alert(jsonDate);

           var currentDate = eval(jsonDate.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"));

           alert(currentDate);            

       }

   </script>

You will see that in the second alert you will get back the normal date values.

As for the different time zones, it mostly depends of the case scenario you are doing.

Hope this was helpful.

# re: Serialize only specific class properties to JSON string using JavaScriptSerializer

Thursday, August 11, 2011 5:18 AM by Yousef_Jadallah

Great topic.

Leave a Comment

(required) 
(required) 
(optional)
(required)