Quantcast
Channel: RobVolk.com » LINQ
Viewing all articles
Browse latest Browse all 3

Using LINQ to Serialize a C# Object into JSON

$
0
0

The Problem

You have a complex object and you need to serialize it into JSON (JavaScript Object Notation).  But your client code only needs one of the properties.  So why serialize the whole thing?

The Solution:

LINQ to Objects + JavaScriptSerializer

With LINQ, you can very easily create an array of strings from one property of the complex object.  Notice the ‘var’ keyword – the variable type is determined at compile time.  This requires .NET 3.5.

Check it out

class People
{
    public string Name { get; set; }
    public string OtherData { get; set; }
}

void CreateNamesJavascript()
{
    List<People> people = new List<People>();
    people.Add(new People() { Name = "Bobby Chaz" });
    people.Add(new People() { Name = "Omar" });

    // build an array of names with LINQ
    var names = from person in people
                select person.Name;

    // serialize the names to JSON
    JavaScriptSerializer jss = new JavaScriptSerializer();
    string json = jss.Serialize(names);

    // using a LiteralControl in ASP.NET Web Forms.
    // for MVC, just use Json() to serialize and return the JSON
    LiteralControl script = new LiteralControl();
    script.Text = string.Format(string.Format(@"<script language=""javascript"" type=""text/javascript"">
        <!--
        var names = {1};
        //-->
        </script>", json));

    Controls.Add(script);
}

Notice the LINQ code (from…select).  It’s very compact and elimates the need to declare a list, create for loops, etc just to get the array we want.  You can also wrap the from..select statement in parenthesis and call .ToArray(), .ToList(), etc.

Next we use JavaScriptSerializer to convert the array to JSON.

The Output

<script language="javascript" type="text/javascript">
<!--
var names = ["Bobby Chaz","Omar"];
//-->
</script>

I highly recommend playing around with LINQ to Objects and LINQ to XML.  It’s very cool and very progressive.

The post Using LINQ to Serialize a C# Object into JSON appeared first on RobVolk.com.


Viewing all articles
Browse latest Browse all 3

Trending Articles