c# 把 json 语句转换成 json 对象(小例子)原创
金蝶云社区-袁袁袁袁袁袁袁
袁袁袁袁袁袁袁
9人赞赏了该文章 371次浏览 未经作者许可,禁止转载编辑于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);
            }
        }
    }
}



image.png






赞 9