Json序列化之.NET开源类库Newtonsoft.Json
上代码:
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[]["Name"].ToString();
Console.WriteLine("数组型数据取法一:" + name1);
Console.WriteLine();
JObject o = (JObject)ja[];
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[].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("");
writer.WriteEndObject();
writer.Flush();
string jsonTextb = sw.GetStringBuilder().ToString();
Console.WriteLine(jsonTextb);
Console.WriteLine(); //序列化Student类
Student stu = new Student() { Name="Jack",Age=};
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<Customer> _list = JsonConvert.DeserializeObject<List<Customer>>(jsonTextc);
//读取列表中的值
Console.WriteLine(_list[].a); //输出结果:aaa2
foreach (Customer c in _list)
{
Console.WriteLine(c.c); //输出结果ccc ccc2
}
Console.WriteLine(); //序列化集合列表
List<Student> students=new List<Student>();
Student stu1=new Student(){Name="Jack",Age=};
Student stu2=new Student(){Name="Tom",Age=};
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<Student2> student2s=new List<Student2>();
Student2 stu3=new Student2(){Name="Jack",Age=,Phones = new List<string>{"",""}};
Student2 stu4 = new Student2() { Name = "Tom", Age = , Phones = new List<string> { "", "" } };
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();
} /// <summary>
/// 遍历动态json对象
/// </summary>
/// <param name="jToken">json对象的集合</param>
/// <param name="key">json对象的属性</param>
/// <returns>json对象的值</returns>
public static string GetJsonValue(JEnumerable<JToken> 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;
} /// <summary>
/// Student类,序列化时用
/// </summary>
public class Student
{
/// <summary>
/// 姓名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 年龄
/// </summary>
public int Age { get; set; }
}
/// <summary>
/// 修改Studnet类,添加电话号码字段
/// </summary>
public class Student2
{
/// <summary>
/// 姓名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 年龄
/// </summary>
public int Age { get; set; }
//电话集合
public List<string> Phones { get; set; }
} /// <summary>
///Customer 的摘要说明
/// </summary>
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<WxPayHtml>(implResult.ReturnValue.PayInfo.Replace("package", "packagevalue")); //public class WxPrePayIdResponse
//{
// public WxPayHtml PayHtml { get; set; }
//} ///// <summary>
///// 微信要序列成对象的实体参数
///// </summary>
//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
/// <summary>
/// JSON Serializer using JavaScriptSerializer
/// </summary>
public class DefaultJsonSerializer : IJsonSerializer
{
private readonly JavaScriptSerializer serializer = new JavaScriptSerializer(); /// <summary>
/// Serialize an object to JSON string
/// </summary>
/// <param name="obj">object</param>
/// <returns>JSON string</returns>
public string Serialize(object obj)
{
return serializer.Serialize(obj);
} /// <summary>
/// Deserialize a JSON string to typed object.
/// </summary>
/// <typeparam name="T">type of object</typeparam>
/// <param name="json">JSON string</param>
/// <returns>typed object</returns>
public T Deserialize<T>(string json)
{
return serializer.Deserialize<T>(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<T>(string json)
{
return JsonSerializer.DeserializeFromString<T>(json);
}
} public class NewtonJsonSerializer : IJsonSerializer
{
public string Serialize(object obj)
{
return JsonConvert.SerializeObject(obj);
} public T Deserialize<T>(string json)
{
return JsonConvert.DeserializeObject<T>(json);
}
}
}
/// <summary>
/// Provides JSON Serialize and Deserialize. Allows custom serializers used.
/// </summary>
public interface IJsonSerializer
{
/// <summary>
/// Serialize an object to JSON string
/// </summary>
/// <param name="obj">object</param>
/// <returns>JSON string</returns>
string Serialize(object obj); /// <summary>
/// Deserialize a JSON string to typed object.
/// </summary>
/// <typeparam name="T">type of object</typeparam>
/// <param name="json">JSON string</param>
/// <returns>typed object</returns>
T Deserialize<T>(string json);
}
https://www.cnblogs.com/yanweidie/p/4605212.html Newtonsoft.Json高级用法
ServiceStack.Text.JsnSerializer
Json序列化之.NET开源类库Newtonsoft.Json的更多相关文章
- Json序列化之.NET开源类库Newtonsoft.Json的研究
一.Json简介 JSON(全称为JavaScript Object Notation) 是一种轻量级的数据交换格式.它是基于JavaScript语法标准的一个子集. JSON采用完全独立于语言的文 ...
- EntityFramework中Json序列化的循环引用问题解决--Newtonsoft.Json
1.在使用EF时,由于数据库主外键关联,将对象进行Json序列化时会遇到循环引用的问题 //EF 中由于数据库主外键关联,对象的序列化经常出现循环引用问题 //使用.Net 自带的序列化工具,序列化出 ...
- C# Json 序列化和反序列化 工具类 Newtonsoft.Json.dll
引用: Newtonsoft.Json.dll // 引用: using Newtonsoft.Json; using Newtonsoft.Json.Converters; // 定义 实体测试类 ...
- [Swift通天遁地]七、数据与安全-(3)Cocopods的安装和开源类库对JSON的解析
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs. ...
- Swifter.Json 可能是 .Net 平台迄今为止性能最佳的 Json 序列化库【开源】
Json 简介 Json (JavaScript Object Notation) 是一种轻量级的数据交换格式.它作为目前最欢迎的数据交换格式,也是各大开源贡献者的必争之地,如:阿里爸爸的 fastj ...
- 解决MVC Json序列化的循环引用问题/EF Json序列化循引用问题---Newtonsoft.Json
1..Net开源Json序列化工具Newtonsoft.Json中提供了解决序列化的循环引用问题: 方式1:指定Json序列化配置为 ReferenceLoopHandling.Ignore 方式2: ...
- MVC web api 返回JSON的几种方式,Newtonsoft.Json序列化日期时间去T的几种方式。
原文链接:https://www.muhanxue.com/essays/2015/01/8623699.html MVC web api 返回JSON的几种方式 1.在WebApiConfig的Re ...
- C#实现JSON序列化与反序列化
1.使用 JavaScriptSerializer类实现序列化 namespace: System.Web.Script.Serialization eg: // 序列化 private string ...
- Json序列化对象
之前都是用的二进制的序列化方法,是.net自带的,但是最常用到的还是Json序列化 (1)只需要调用 Newtonsoft.Json.dll 即可 public class JsonTools { / ...
随机推荐
- Linux下OOM Killer机制详解
http://www.cnblogs.com/ylqmf/archive/2012/11/05/2754795.html http://wuquan-1230.blog.163.com/blog/st ...
- LeetCode89:Gray Code
The gray code is a binary numeral system where two successive values differ in only one bit. Given a ...
- python核心模块之pickle和cPickle解说
pickle模块使用的数据格式是python专用的,而且不同版本号不向后兼容,同一时候也不能被其它语言说识别.要和其它语言交互,能够使用内置的json包使用pickle模块你能够把Python对象直接 ...
- 传输层TCPUDP 具体解释
1.传输层存在的必要性 因为网络层的分组传输是不可靠的,无法了解数据到达终点的时间,无法了解数据未达终点的状态.因此有必要增强网络层提供服务的服务质量. 2.引入传输层的原因 面向连接的传输服务与面向 ...
- Java ClassLoader加载机制理解 实际例子
针对 Java ClassLoader加载机制理解, 做了个如何自定制简单的ClassLoader,并成功加载指定的类. 不废话,直接上代码. package com.chq.study.cl; im ...
- Unity接入谷歌支付
文章理由 前段时间负责Unity接入Google内购功能,一开始研究别人的技术博客时发现,他们的文章都有些年头了,有些细节的地方已经不像n年前那样了,技术永远是需要更新的,而这篇就作为2016年末的最 ...
- [Clojure] A Room-Escape game, playing with telnet and pure-text commands - Part 1
Code path: https://github.com/bluesilence/Lisp/tree/master/clojure/projects/room-escape As I have be ...
- Istio在Openshift 3.11的安装
详细安装步骤及解释参考 https://docs.openshift.com/container-platform/3.11/servicemesh-install/servicemesh-insta ...
- informatica powercenter学习笔记(二)
LOOKUP TRANSFORMATION的使用点评: LOOKUP基本用法不熟的话请参考下附属信息. 用法感受: 1 LOOKUP的作用跟我们以前在EXCEL的函数功能类似,就是隔表取值.优点就是用 ...
- VS2010 OpenCL运行环境配置
1.安装AMD GPU显卡驱动(安装后重启) 13-12_win7_win8_64_dd_ccc_whql.exe 2.安装AMD OpenCL SDK(安装后重启) AMD-APP-SDK-v2.9 ...