json字符窜转对象
第一种方法:
注意引用:using System.Runtime.Serialization.Json; using System.IO; static void Main(string[] args) { //IRace human = new Human(); //human.Showking(); //IRace orc =new Orc(); //orc.Showking(); var returnCitySN = "{ \"cip\": \"183.39.52.39\", \"cid\": \"440300\", \"cname\": \"广东省深圳市\"}"; Class1 class1 = ParseFormJson<Class1>(returnCitySN); Console.ReadKey(); } public static T ParseFormJson<T>(string szJson) { T obj = Activator.CreateInstance<T>(); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson))) { DataContractJsonSerializer dcj = new DataContractJsonSerializer(typeof(T)); return (T)dcj.ReadObject(ms); } }
第二种方法:
//使用Json.NET类库需要引入的命名空间 //----------------------------------------------------------------------------- using Newtonsoft.Json; //------------------------------------------------------------------------- EastGroup jsonEast = JsonConvert.DeserializeObject<EastGroup>(strLine);//反序列化