-
using System;
-
using System.Collections.Generic;
-
using System.Linq;
-
using System.Text;
-
using System.Web.Script.Serialization;
-
using System.IO;
-
using Newtonsoft.Json;
-
-
namespace JsonTest
-
{
-
class Person
-
{
-
public string name { get; set; }
-
public int age { get; set; }
-
public override string ToString()
-
{
-
return String.Format("Name : {0}\nAge : {1}",name,age);
-
}
-
}
-
class Program
-
{
-
static void Main(string[] args)
-
{
-
-
-
//方法一:
-
//Serialization class
-
!important;">;
-
//deserialize json from file
-
string Jsonsting = File.ReadAllText("Json.json");
-
Person p1 = ser.Deserialize(Jsonsting);
-
Console.WriteLine(p1);
-
-
//output json file
-
Person p2 = new Person() {name="ben",age=23 };
-
string outputJson = ser.Serialize(p2);
-
File.WriteAllText("output.json",outputJson);
-
-
//方法二:
-
//Newtonsoft.Json --->Json.NET library
-
//deserialize json from file
-
string Jsonsting1 = File.ReadAllText("Json.json");
-
Person p3 = JsonConvert.DeserializeObject(Jsonsting1);
-
Console.WriteLine(p1);
-
-
//output json file
-
Person p4 = new Person() { name = "ben", age = 23 };
-
string outputJson1 = JsonConvert.SerializeObject(p4);
-
File.WriteAllText("output1.json", outputJson1);
-
-
Console.ReadKey();
-
-
-
}
-
}
-
}
备注:
(1)Serialization类需要引用: System.Web.Extensions
(2) Newtonsoft.Json类,需要在Nuget中安装json.net
\