博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Json序列化之.NET开源类库Newtonsoft.Json
阅读量:5161 次
发布时间:2019-06-13

本文共 10069 字,大约阅读时间需要 33 分钟。

上代码: 

using System;using System.Collections;using System.Collections.Generic;using System.IO;using System.Linq;using System.Text;using Newtonsoft.Json;using Newtonsoft.Json.Linq; namespace JsonWithNewtonsoft{    class Program    {        static void Main(string[] args)        {            //使用StringReader读取Json            string jsonText = @"{""Name"":""Jack"",""Age"":""22""}";            JsonReader reader = new JsonTextReader(new StringReader(jsonText));            while (reader.Read())            {                Console.WriteLine(reader.TokenType + "\t" + reader.ValueType + "\t" + reader.Value);            }            Console.WriteLine();            //使用JObject读取Json            JObject jo = JObject.Parse(jsonText);            string[] values = jo.Properties().Select(item => item.Name.ToString() + ":" + item.Value.ToString()).ToArray();            foreach (string s in values)            {                Console.WriteLine(s);            }            Console.WriteLine();            //解析数组型数据            string jsonArrayText1 = "[{'Name':'Tom','Age':'16'},{'Name':'Mary','Age':'15'}]";            JArray ja = (JArray)JsonConvert.DeserializeObject(jsonArrayText1);            string name1 = ja[1]["Name"].ToString();            Console.WriteLine("数组型数据取法一:" + name1);            Console.WriteLine();            JObject o = (JObject)ja[1];            string name2 = o["Name"].ToString();            Console.WriteLine("数组型数据取法二:" + name2);            Console.WriteLine();            //嵌套格式            string jsonTexta = "{\"shanghai\":{\"zone\":\"浦东\",\"zone_en\":\"pudong\"}}";            JObject jsonObjt = JObject.Parse(jsonTexta);            string zone = ((JObject)jsonObjt["shanghai"])["zone"].ToString();            string zoneEn = ((JObject)jsonObjt["shanghai"])["zone_en"].ToString();            Console.WriteLine(zone + "," + zoneEn);            string jsonData = "{\"name\":\"lily\",\"age\":23,\"addr\":{\"city\":\"guangzhou\",\"province\":\"guangdong\"}}";            JObject jsonObj = JObject.Parse(jsonData);            string namea = jsonObj["name"].ToString();            string age = jsonObj["age"].ToString();            string city = ((JObject)jsonObj["addr"])["city"].ToString();            string province = ((JObject)jsonObj["addr"])["province"].ToString();            Console.WriteLine(namea + "," + age + "," + city + "," + province);            Console.WriteLine(GetJsonValue(jsonObj.Children(), "province"));            Console.WriteLine();            string jsonDatab = "{\"addr\":[{\"city\":\"guangzhou\",\"province\":\"guangdong\"},{\"city\":\"guiyang\",\"province\":\"guizhou\"}]}";            JObject jsonObjm = JObject.Parse(jsonDatab);            JArray jar = JArray.Parse(jsonObjm["addr"].ToString());            JObject j = JObject.Parse(jar[0].ToString());            Console.WriteLine(j["city"]);                        //序列化Json            StringWriter sw = new StringWriter();            JsonWriter writer = new JsonTextWriter(sw);            writer.WriteStartObject();            writer.WritePropertyName("Name");            writer.WriteValue("Jack");            writer.WritePropertyName("Age");            writer.WriteValue("26");            writer.WriteEndObject();            writer.Flush();            string jsonTextb = sw.GetStringBuilder().ToString();            Console.WriteLine(jsonTextb);            Console.WriteLine();            //序列化Student类            Student stu = new Student() { Name="Jack",Age=20};            JsonSerializer serializer=new JsonSerializer();            StringWriter strw=new StringWriter();            serializer.Serialize(new JsonTextWriter(strw),stu );            Console.WriteLine(strw.GetStringBuilder().ToString());            //反序列化Student类            StringReader sr=new StringReader(strw.GetStringBuilder().ToString());            Student st = (Student) serializer.Deserialize(new JsonTextReader(sr), typeof (Student));            Console.WriteLine(st.Name + "=>" + st.Age);             Console.WriteLine();            //反序列化类            //定义一个JSON字符串               string jsonTextc = "[{'a':'aaa','b':'bbb','c':'ccc'},{'a':'aaa2','b':'bbb2','c':'ccc2'}]";            //反序列化JSON字符串,将JSON字符串转换成LIST列表              List
_list = JsonConvert.DeserializeObject
>(jsonTextc); //读取列表中的值 Console.WriteLine(_list[1].a); //输出结果:aaa2 foreach (Customer c in _list) { Console.WriteLine(c.c); //输出结果ccc ccc2 } Console.WriteLine(); //序列化集合列表 List
students=new List
(); Student stu1=new Student(){Name="Jack",Age=20}; Student stu2=new Student(){Name="Tom",Age=21}; students.Add(stu1); students.Add(stu2); JsonSerializer serializer1=new JsonSerializer(); StringWriter strw1=new StringWriter(); serializer.Serialize(new JsonTextWriter(strw1),students); Console.WriteLine(strw1.GetStringBuilder().ToString()); Console.WriteLine(); List
student2s=new List
(); Student2 stu3=new Student2(){Name="Jack",Age=20,Phones = new List
{ "18627900216","18571643691"}}; Student2 stu4 = new Student2() { Name = "Tom", Age = 21, Phones = new List
{ "15972944805", "13349855388" } }; student2s.Add(stu3); student2s.Add(stu4); JsonSerializer serializer2=new JsonSerializer(); StringWriter strw2=new StringWriter(); serializer2.Serialize(new JsonTextWriter(strw2),student2s); Console.WriteLine(strw2.GetStringBuilder().ToString()); Console.Read(); } ///
/// 遍历动态json对象 /// ///
json对象的集合 ///
json对象的属性 ///
json对象的值
public static string GetJsonValue(JEnumerable
jToken, string key) { IEnumerator enumerator = jToken.GetEnumerator(); while (enumerator.MoveNext()) { JToken jc = (JToken) enumerator.Current; if (jc is JObject || ((JProperty) jc).Value is JObject) { return GetJsonValue(jc.Children(), key); } else { if (((JProperty) jc).Name == key) { return ((JProperty) jc).Value.ToString(); } } } return null; } ///
/// Student类,序列化时用 /// public class Student { ///
/// 姓名 /// public string Name { get; set; } ///
/// 年龄 /// public int Age { get; set; } } ///
/// 修改Studnet类,添加电话号码字段 /// public class Student2 { ///
/// 姓名 /// public string Name { get; set; } ///
/// 年龄 /// public int Age { get; set; } //电话集合 public List
Phones { get; set; } } ///
///Customer 的摘要说明 /// public class Customer { //在序列化前后没有变动 public string a { get; set; } //在序列化前后设置和重置 public string b { get; set; } //设置为null,但在序列化后填充 public string c { get; set; } public string Other { get; set; } public Customer() { // //TODO: 在此处添加构造函数逻辑 // a = ""; b = ""; c = ""; Other = null; } } //应用实例: //result.Data.PayHtml = JsonConvert.DeserializeObject
(implResult.ReturnValue.PayInfo.Replace("package", "packagevalue")); //public class WxPrePayIdResponse //{ // public WxPayHtml PayHtml { get; set; } //} /////
///// 微信要序列成对象的实体参数 ///// //public class WxPayHtml //{ // public string appid { get; set; } // public string partnerid { get; set; } // public string prepayid { get; set; } // public string noncestr { get; set; } // public string timestamp { get; set; } // public string appkey { get; set; } // public string packagevalue { get; set; } // public string sign { get; set; } //}

/*"PayHtml": {

"appid": "wx257b0d84993abd65",
"partnerid": "1223710101",
"prepayid": "8201038000151225260ec7a972158a17",
"noncestr": "41c542dfe6e4fc3deb251d64cf6ed2e4",
"timestamp": "1451053391",
"appkey": "4VAICNn3cH84oUgvIPiQiRFCxYTmvCMqGl4Afk4dxZsgXGCudgf8tvkKPU40HAXa4M4NOCTN9o4NqbSD7Vo3jd9w3ulZ4l69BG0xlpAQYyjDVMk9brEv4v7HA2kswARc",
"packagevalue": "Sign=WXPay",
"sign": "e0c1075e4f53f8ed40d37719c3a2a4bac8994f23"
}*/

}}

 

上效果:

上附件:

 

引用  System.Web.Extensions

///     /// JSON Serializer using JavaScriptSerializer    ///     public class DefaultJsonSerializer : IJsonSerializer    {        private readonly JavaScriptSerializer serializer = new JavaScriptSerializer();        ///         /// Serialize an object to JSON string        ///         /// object        /// 
JSON string
public string Serialize(object obj) { return serializer.Serialize(obj); } /// /// Deserialize a JSON string to typed object. /// ///
type of object
/// JSON string ///
typed object
public T Deserialize
(string json) { return serializer.Deserialize
(json); } }

 

using Newtonsoft.Json;using JsonSerializer = ServiceStack.Text.JsonSerializer;namespace JWT.Tests{    public class ServiceStackJsonSerializer : IJsonSerializer    {        public string Serialize(object obj)        {            return JsonSerializer.SerializeToString(obj);        }        public T Deserialize
(string json) { return JsonSerializer.DeserializeFromString
(json); } } public class NewtonJsonSerializer : IJsonSerializer { public string Serialize(object obj) { return JsonConvert.SerializeObject(obj); } public T Deserialize
(string json) { return JsonConvert.DeserializeObject
(json); } }}

 

///     /// Provides JSON Serialize and Deserialize.  Allows custom serializers used.    ///     public interface IJsonSerializer    {        ///         /// Serialize an object to JSON string        ///         /// object        /// 
JSON string
string Serialize(object obj); /// /// Deserialize a JSON string to typed object. /// ///
type of object
/// JSON string ///
typed object
T Deserialize
(string json); }

 

https://www.cnblogs.com/yanweidie/p/4605212.html     Newtonsoft.Json高级用法 

 

ServiceStack.Text.JsnSerializer

转载于:https://www.cnblogs.com/shy1766IT/p/5028908.html

你可能感兴趣的文章
vue实战(7):完整开发登录页面(一)
查看>>
[转载]mysql的left,right,substr,instr截取字符串,截取
查看>>
Visual Studio自定义模板(二)
查看>>
【Mood-20】滴滤咖啡做法 IT工程师加班必备 更健康的coffee 项目经理加班密鉴
查看>>
读《构建之法-软件工程》第四章有感
查看>>
使用 Printf via SWO/SWV 输出调试信息
查看>>
.net 分布式架构之分布式锁实现(转)
查看>>
吴恩达机器学习笔记 —— 3 线性回归回顾
查看>>
Problem E: Automatic Editing
查看>>
SpringBoot 使用 MyBatis 分页插件 PageHelper 进行分页查询
查看>>
《DSP using MATLAB》Problem 6.17
查看>>
微信公众平台开发实战Java版之如何网页授权获取用户基本信息
查看>>
一周TDD小结
查看>>
sizeof与strlen的用法
查看>>
Linux 下常见目录及其功能
查看>>
开源框架中常用的php函数
查看>>
nginx 的提升多个小文件访问的性能模块
查看>>
set&map
查看>>
集合类总结
查看>>
4.AE中的缩放,书签
查看>>