Newtonsoft.Json
Microsoft.AspNetCore.Mvc.NewtonsoftJson
JsonConvert.DeserializeObject<T>(string json)//反序列化 JsonConvert.SerializeObject(object obj) //序列化
public class Person { public int Age { get; set; } public string Name { get; set; } [JsonIgnore] public string Sex { get; set; } }
public class Person { public int Age { get; set; } public string Name { get; set; } [JsonProperty(PropertyName = "SepcialSex")] public string Sex { get; set; } }
//构建一个json对象,描述了一个老师的实体,里面包含老师的基本属性(名称、年龄),所管理的班级属性,所管理的班级的学生数组 dynamic teacher = new { name = "张三", age = 51, classRoom = new { name = "1年级1班", desc = "描述" }, students = new[] { new { name = "小明" }, new { name = "小红" } } }; //序列化 string jsonStr = JsonConvert.SerializeObject(teacher);
jsonStr = "{\"name\":null,\"age\":null,\"classroom\":{\"name\":\"1年级1班\",\"desc\":\"描述\"},\"students\":[{\"name\":\"小名\"},{\"name\":\"小红\"}]}"; JObject jTeacher = JObject.Parse(jsonStr); //获取一级数据 .Value<T>方式 / ToString() 方式 string teacherName = jTeacher["name"].Value<string>();//区分大小写,没有会报异常 string teacherGender = jTeacher["gender"].ToString();//区分大小写,没有会报异常 int? teacherAge = jTeacher["age"].Value<int?>();//数字如果是null,而接收类型不是可空类型,则会报异常
string className = jTeacher["classRoom"]["name"].Value<string>();
if (jTeacher.Property("name") != null) { Console.WriteLine("有"); }
//jTeacher["students"].Value<string>();//这个是错误的,数组无法转为string JArray students = JArray.Parse(jTeacher["students"].ToString());//null或者""都会报错 foreach (var item in students) { string studentName = item["name"].Value<string>(); }
foreach (JProperty item in obj.Children()) { Console.WriteLine("Name=" + item.Name + "-Value=" + item.Value); }
JObject obj = new JObject(); obj.Add("ID", 1); obj.Add("Name", "张三"); obj.Add("Birthday", DateTime.Parse("2000-01-02")); obj.Add("IsVIP", true); obj.Add("Account", 12.34f);
JArray array = new JArray(); array.Add(new JValue("吃饭")); array.Add(new JValue("睡觉")); obj.Add("Favorites", array); obj.Add("Remark", null); JArray array1 = new JArray("吃饭", "睡觉");
/// <summary>添加一个属性 /// C#给JSON对象添加一个键值对 /// </summary> /// <param name="obj">待添加属性的对象</param> /// <param name="key">键名</param> /// <param name="value">值</param> /// <returns>添加属性后的对象</returns> public static object Add(object obj, string key, object value) { JObject jObj = JObject.Parse(JsonConvert.SerializeObject(obj)); jObj.Add(new JProperty(key, value)); return JsonConvert.DeserializeObject(jObj.ToString()); }
/// <summary>添加一个属性 /// C#给JSON字符串添加一个键值对 /// </summary> /// <param name="obj">待添加属性的对象</param> /// <param name="key">键名</param> /// <param name="value">值</param> /// <returns>添加属性后的对象</returns> public static object AddStr(string obj, string key, object value) { JObject jObj = JObject.Parse(obj); jObj.Add(new JProperty(key, value)); return JsonConvert.DeserializeObject(jObj.ToString()); }
.net 5.0 - Newtonsoft.Json JObject / JArray
原文:https://www.cnblogs.com/gygtech/p/14806772.html