irpas技术客

C#开发获取json数据并转换为string类型_c# json转string_8983165xld

网络 8201

1.根据需要创建class json数据结构: {“name”:“张三”,“age”:20,“idCard”:“123456789”,“birthday”:“2021-01-01 00:00:00”,“hobbys”:[{“sort”:1,“desc”":“写字”},{“sort”:2,“desc”:“游泳”}]} private class Studet { public string name { get; set; } public int age { get; set; } public string idCard { get; set; } public DateTime birthday { get; set; } public List hobbys { get; set; } } private class hobby { public int sort { get; set; } public string desc { get; set; }

}

2.应用dll文件Newtonsoft.Json 添加命名空间 using Newtonsoft.Json; using Newtonsoft.Json.Linq; 需要用到里面的json方法 创建数组并将实例添加进去 //定义数组并将值添加到数组中 List hobby = new List(); hobby.Add(new hobby { sort = 1, desc = “写字” }); hobby.Add(new hobby { sort = 2, desc = “游泳” }); 创建对象添加实例 JObject jsoure = new JObject(); jsoure.Add(“name”,“张三”); jsoure.Add(“age”,20); jsoure.Add(“idCard”,“123456788”); jsoure.Add(“birthday”,“2021-01-01 12:34:23”); jsoure.Add(“hobbys”, JToken.FromObject(hobby)); 实例化:

Studet student = JsonConvert.DeserializeObject<Studet>(jsoure.ToString());//将jobject转换为string类型 //输出:张三 Console.WriteLine(student.age); Console.Write(student.birthday); Console.ReadLine(); for (int i = 0; i <= student.hobbys.Count; i++) { Console.WriteLine(student.hobbys[i].sort); Console.WriteLine(student.hobbys[i].desc); }

效果图:

参考的博客文章: https://blog.csdn.net/weixin_43151418/article/details/127409818?utm_medium=distribute.pc_relevant.none-task-blog-2defaultbaidujs_baidulandingword~default-0-127409818-blog-123168592.pc_relevant_recovery_v2&spm=1001.2101.3001.4242.1&utm_relevant_index=3


1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,会注明原创字样,如未注明都非原创,如有侵权请联系删除!;3.作者投稿可能会经我们编辑修改或补充;4.本站不提供任何储存功能只提供收集或者投稿人的网盘链接。

标签: #C #json转string #C开发json解析本人亲测有效