Monday, February 6, 2012

What is JsonValue?

JsonValue is the abstract base class for JavaScript Object Notation (JSON) common language runtime (CLR) types.
If we get JsonValue package from nuget in VS2010, then the application will have a reference to Microsoft.Json.dll that will provide System.Json.JsonValue datatype. JsonValue is the abstarct base class and the JSON CLR types JsonPrimitive, JsonArray, and JsonObject all inherit from this base class.
this is very useful when we need to create or parse json data.
Here is an example how to use it.
This method will grab all catalog entites from database using entity framework code first and then it will return only two properties of those entities as json data.

public System.Json.JsonValue GetCatalogs()
    DbContext context = new MyContext();
    DbSet<T> dbSet = context.Set<Catalog>();
    var list = dbSet.Select(s => new { s.CatalogId, s.CatName }).ToList();
    var results = new System.Json.JsonArray();
    foreach (var item in list)
        dynamic obj = new System.Json.JsonObject();
        obj.CatalogId = item.CatalogId;
        obj.CatName = item.CatalogId;
    return results;


Post a Comment