Simple example (you need .NET 3.5):
The main class is DataContractJsonSerializer
...
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
namespace JSonExample
{
[DataContract]
public class Person
{
[DataMember(Name = "Name")]
public string Name { get; set; }
[DataMember(Name = "Age")]
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
var customer = new Person {Age = 25, Name = "Albert"};
string jSon = JSONSerializer<Person>.Serialize(customer);
//{"Age":25,"Name":"Albert"}
var deserializedCustomr = JSONSerializer<Person>.DeSerialize(jSon);
}
}
public static class JSONSerializer<T> where T : class
{
/// <summary>
/// Serializes an object to JSON
/// </summary>
public static string Serialize(T instance)
{
var serializer = new DataContractJsonSerializer(typeof(T));
using (var stream = new MemoryStream())
{
serializer.WriteObject(stream,
instance);
return Encoding.Default.GetString(stream.ToArray());
}
}
/// <summary>
/// DeSerializes an object from JSON
/// </summary>
public static T DeSerialize(string json)
{
using (var stream = new MemoryStream(Encoding.Default.GetBytes(json)))
{
var serializer = new DataContractJsonSerializer(typeof(T));
return serializer.ReadObject(stream) as T;
}
}
}
}
Žiadne komentáre:
Zverejnenie komentára