Convert objects to JSON in C# using JavaScriptSerializer
2010-05-25 20:52
519 查看
Want to convert a C# object into it's JSON equivalent? Here is a simple object from the System.Web.Script namespace that does exactly that:
System.Web.Script.Serialization.JavaScriptSerializer . It is stored in the System.Web.Extentions DLL (.Net Framework 3.5 only)
Using this object we serialize and deserialize objects in C#. Here is a quick sample:
A simple Employee object:
Adding some instances of them to a List:
Serializing then:
And here is the output:
System.Web.Script.Serialization.JavaScriptSerializer . It is stored in the System.Web.Extentions DLL (.Net Framework 3.5 only)
Using this object we serialize and deserialize objects in C#. Here is a quick sample:
A simple Employee object:
public class Employee { public string Name { get; set; } public string Age { get; set; } public string ID { get; set; } }
Adding some instances of them to a List:
Employee oEmployee1 =
new Employee{Name="Pini",ID="111", Age="30"};
Employee oEmployee2 =
new Employee { Name = "Yaniv", ID = "Cohen", Age = "31" }; Employee oEmployee3 =
new Employee { Name = "Yoni", ID = "Biton", Age = "20" };
List<Employee> oList = new List<Employee>()
{ oEmployee1, oEmployee2, oEmployee3 };
Serializing then:
System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer(); string sJSON = oSerializer.Serialize(oList);
And here is the output:
[{"Name":"Pini","Age":"30","ID":"111"},
{"Name":"Yaniv","Age":"31","ID":"Cohen"},
{"Name":"Yoni","Age":"20","ID":"Biton"}]
相关文章推荐
- Convert objects to JSON in C# using JavaScriptSerializer
- Convert objects to JSON in C# using JavaScriptSerializer
- using JavaScriptSerializer to serialize object to json
- How to convert XML to JSON in ASP.NET C#
- Send and Receive JSON objects to Web Service Methods using jQuery AJAX in ASP.Net
- How to convert XML to JSON in ASP.NET C#
- csharp:Learn how to post JSON string to generic Handler using jQuery in ASP.Net C#.
- [Immutable.js] Using fromJS() to Convert Plain JavaScript Objects into Immutable Data
- Convert object to json and json to object in C#
- C# JavaScriptSerializer报错,json数据太长
- C# in Depth (第十一章 查询表达式和LINQ to Objects)
- Gson is a Java library that can be used to convert Java Objects into their JSON representation.
- csharp:Learn how to post JSON string to generic Handler using jQuery in ASP.Net
- 【javascript】Convert any colour value to hex in MSIE
- How to avoid using() mistake in C#?
- How To Work With JSON In Node.js / JavaScript
- Using canvas to do bitmap sprite animation in JavaScript
- Writing a full JSON Serializer in 100 lines of C# code
- How to convert an IPv4 address into a integer in C#?
- How to close (auto hide) WPF window after 10 sec using a timer in C#?