c# 把 json 语句转换成 json 对象(小例子)原创
9人赞赏了该文章
508次浏览
编辑于2023年11月16日 15:34:04
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Kingdee.BOS.JSON; using Newtonsoft.Json; using System; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace C_Sharp_XueXi { class Program { static void Main(string[] args) { // JSON字符串 string json = @" { ""Name"": ""Alice"", ""Age"": 25, ""City"": ""New York"", ""Pets"": [ { ""Name"": ""Fluffy"", ""Type"": ""Cat"" }, { ""Name"": ""Fido"", ""Type"": ""Dog"" } ], ""Friends"": [ { ""Name"": ""Bob"", ""Age"": 30, ""City"": ""Chicago"" }, { ""Name"": ""Eve"", ""Age"": 28, ""City"": ""San Francisco"" } ] }"; // 解析JSON字符串 JObject jsonObj = JObject.Parse(json); // 获取特定字段的值 string name = (string)jsonObj["Name"]; int age = (int)jsonObj["Age"]; string city = (string)jsonObj["City"]; // 获取数组字段的值 JArray pets = (JArray)jsonObj["Pets"]; foreach (JObject pet in pets) { string petName = (string)pet["Name"]; string petType = (string)pet["Type"]; Console.WriteLine("Pet: Name = {0}, Type = {1}", petName, petType); } // 获取嵌套对象字段的值 JArray friends = (JArray)jsonObj["Friends"]; foreach (JObject friend in friends) { string friendName = (string)friend["Name"]; int friendAge = (int)friend["Age"]; string friendCity = (string)friend["City"]; Console.WriteLine("Friend: Name = {0}, Age = {1}, City = {2}", friendName, friendAge, friendCity); } } } }
赞 9
9人点赞
还没有人点赞,快来当第一个点赞的人吧!
打赏
0人打赏
还没有人打赏,快来当第一个打赏的人吧!
推荐阅读