DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Commonly Occurring Errors in Microsoft Graph Integrations and How To Troubleshoot Them (Part 4)
  • Modify JSON Data in Postgres and Hibernate 6
  • Proper Java Exception Handling
  • JSON-Based Serialized LOB Pattern

Trending

  • From "Vibe Coding" to Production: Setting Up an Evals Loop for Claude Agents
  • Observability for Agents and Workflows: Tracing Prompts, Tool Calls, and Business Outcomes End-to-End
  • DZone's Article Submission Guidelines
  • Combining Temporal and Kafka for Resilient Distributed Systems
  1. DZone
  2. Data Engineering
  3. Data
  4. Serialize only specific class properties to JSON string using JavaScriptSerializer

Serialize only specific class properties to JSON string using JavaScriptSerializer

By 
Hajan Selmani user avatar
Hajan Selmani
·
Aug. 10, 11 · News
Likes (0)
Comment
Save
Tweet
Share
32.2K Views

Join the DZone community and get the full member experience.

Join For Free

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 = "[email protected]"
    });
    customers.Add(new Customer()
    {
        Name = "John",
        Surname = "Doe",
        Age = 29,
        Drinker = false,
        Smoker = true,
        Single = false,
        Email = "[email protected]"
    });
    customers.Add(new Customer()
    {
        Name = "Mark",
        Surname = "Moris",
        Age = 34,
        Drinker = true,
        Smoker = true,
        Single = true,
        Email = "[email protected]"
    });

    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.

Property (programming) JSON Data Types Strings

Published at DZone with permission of Hajan Selmani. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Commonly Occurring Errors in Microsoft Graph Integrations and How To Troubleshoot Them (Part 4)
  • Modify JSON Data in Postgres and Hibernate 6
  • Proper Java Exception Handling
  • JSON-Based Serialized LOB Pattern

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook