Does Microsoft provide any library to work with JSON in C#? If not, what open source library do you recommend? Thanks.
Have a look at the system.web.script.serialization namespace (i think you will need .Net 3.5)
If you look here, you will see several different libraries for JSON on C#.
You will find a version for LINQ as well as some others. There are about 7 libraries for C# and JSON.
Here is a good example to get you started.
using System.Collections.Generic;
using System.Web.Script.Serialization;
namespace GoogleTranslator.GoogleJSON
{
public class FooTest
{
public void Test()
{
const string json = @"{
""DisplayFieldName"" : ""ObjectName"",
""FieldAliases"" : {
""ObjectName"" : ""ObjectName"",
""ObjectType"" : ""ObjectType""
},
""PositionType"" : ""Point"",
""Reference"" : {
""Id"" : 1111
},
""Objects"" : [
{
""Attributes"" : {
""ObjectName"" : ""test name"",
""ObjectType"" : ""test type""
},
""Position"" :
{
""X"" : 5,
""Y"" : 7
}
}
]
}";
var ser = new JavaScriptSerializer();
ser.Deserialize<Foo>(json);
}
}
public class Foo
{
public Foo() { Objects = new List<SubObject>(); }
public string DisplayFieldName { get; set; }
public NameTypePair FieldAliases { get; set; }
public PositionType PositionType { get; set; }
public Ref Reference { get; set; }
public List<SubObject> Objects { get; set; }
}
public class NameTypePair
{
public string ObjectName { get; set; }
public string ObjectType { get; set; }
}
public enum PositionType { None, Point }
public class Ref
{
public int Id { get; set; }
}
public class SubObject
{
public NameTypePair Attributes { get; set; }
public Position Position { get; set; }
}
public class Position
{
public int X { get; set; }
public int Y { get; set; }
}
}
Try the Vici Project, Vici Parser. It includes a JSON parser / tokeniser. It works great, we use it together with the MVC framework.
More info at: http://viciproject.com/wiki/projects/parser/home
I forgot to say that it is open source so you can always take a look at the code if you like.
You should also try my ServiceStack JsonSerializer - it's the fastest .NET JSON serializer at the moment based on the benchmarks of the leading JSON serializers and supports serializing any POCO Type, DataContracts, Lists/Dictionaries, Interfaces, Inheritance, Late-bound objects including anonymous types, etc.
Basic Example
var customer = new Customer { Name="Joe Bloggs", Age=31 };
var json = JsonSerializer.SerializeToString(customer);
var fromJson = JsonSerializer.DeserializeFromString<Customer>(json);
Note: Only use Microsofts JavaScriptSerializer if performance is not important to you as I've had to leave it out of my benchmarks since its up to 40x-100x slower than the other JSON serializers.