csharp 此代码演示了json序列化和反序列化的4种方法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 此代码演示了json序列化和反序列化的4种方法相关的知识,希望对你有一定的参考价值。

class JsonSerializationProgram
{
	static void Main(string[] args)
	{
		var person = new Person
		{
			firstName = "John",
			lastName = "Doe",
			dateOfBirth = new MyDate
			{
				year = 1901,
				month = 4,
				day = 30
			}
		};

		Method1(person);
		Method2(person);
		Method3(person);
		Method4(person);

		Console.WriteLine("\r\nFinished.");
		Console.ReadLine();
	}

	#region Method1
	private static void Method1(Person person)
	{
		var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

		var json = serializer.Serialize(person);

		var anotherObject = serializer.Deserialize(json, typeof(Person));
	}
	#endregion

	#region Method2
	private static void Method2(Person person)
	{
		var json = Newtonsoft.Json.JsonConvert.SerializeObject(person);

		var anotherObject = Newtonsoft.Json.JsonConvert.DeserializeObject<Person>(json);
		var anotherJObject = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(json);
		dynamic anotherDynamicObject = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
	}
	#endregion

	#region Method3
	private static void Method3(Person person)
	{
		var ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(Person));
		var output = "";

		using (var ms = new MemoryStream())
		{
			ser.WriteObject(ms, person);
			output = Encoding.Default.GetString(ms.ToArray());
		}

		using (var ms = new MemoryStream(Encoding.Default.GetBytes(output)))
		{
			var anotherObject = ser.ReadObject(ms) as Person;
		}
	}
	#endregion

	#region Method4
	private static void Method4(Person person)
	{
		var json = NetJSON.NetJSON.Serialize(person);

		var anotherObject = NetJSON.NetJSON.Deserialize<Person>(json);
	}
	#endregion
}

public class MyDate
{
	public int year;
	public int month;
	public int day;
}

public class Person
{
	public string firstName;
	public string lastName;
	public MyDate dateOfBirth;
}

以上是关于csharp 此代码演示了json序列化和反序列化的4种方法的主要内容,如果未能解决你的问题,请参考以下文章

Newtonsoft.Json 序列化和反序列化 以及时间格式 2

将 Objective-C 对象序列化和反序列化为 JSON

unity Restsharp Api Json 序列化和反序列化

ASP.NET 中JSON 的序列化和反序列化

ASP.NET中JSON的序列化和反序列化

ASP.NET中JSON的序列化和反序列化