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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

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

  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 3: Understanding Janus
  • Memory Leak Due to Time-Taking finalize() Method
  • The Ultimate Guide to Code Formatting: Prettier vs ESLint vs Biome
  • How Large Tech Companies Architect Resilient Systems for Millions of Users
  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.0K 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 = "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.

Property (programming) JSON Data Types Strings

Published at DZone with permission of Hajan Selmani, DZone MVB. 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
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!