Create JSON string using object initializer

Tags: json, initializer, serializer

Categories: .NET, C#

Tags: .NET, C#

Suppose we have the following JSON:

    "msg":"User created"

We need to write a simple piece of code to build this JSON string.

Have you ever seen a code similar to the one below?

string successValue = "true";
string msgValue = "User created";

StringBuilder sb = new StringBuilder();
sb.Append("{\"success\" : \"");
sb.Append("\", \"msg\" : \"");

If you think this is the best way of doing it then I will tell you that there is a better, cleaner way of doing it: using object initializer and java script serializer.

The same can be achieved using only a few lines of code:

JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize(
            success = successValue,
            msg = msgValue

How better is this one compared to the first approach?

You will need to add a reference to the System.Web.Extensions library and add using to System.Web.Script.Serialization.


comments powered by Disqus