Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# jsonobject

作者:风中孤狼   发布日期:2026-06-30   浏览:35

using Newtonsoft.Json.Linq;

class Program
{
    static void Main()
    {
        // 创建一个 JSON 对象
        JObject jsonObject = new JObject
        {
            { "name", "John" },
            { "age", 30 },
            { "isStudent", false }
        };

        // 添加嵌套的 JSON 对象
        jsonObject["address"] = new JObject
        {
            { "street", "123 Main St" },
            { "city", "Anytown" },
            { "state", "CA" }
        };

        // 将 JSON 对象转换为字符串
        string jsonString = jsonObject.ToString();
        Console.WriteLine("JSON String: " + jsonString);

        // 从 JSON 字符串解析为 JSON 对象
        string jsonInput = "{\"name\":\"Jane\",\"age\":25,\"isStudent\":true}";
        JObject parsedObject = JObject.Parse(jsonInput);
        Console.WriteLine("Parsed JSON Object: " + parsedObject);

        // 访问 JSON 对象中的属性
        string name = (string)parsedObject["name"];
        int age = (int)parsedObject["age"];
        bool isStudent = (bool)parsedObject["isStudent"];

        Console.WriteLine($"Name: {name}, Age: {age}, Is Student: {isStudent}");
    }
}

解释说明:

  1. 创建 JSON 对象:使用 JObject 类创建一个 JSON 对象,并添加键值对。
  2. 嵌套 JSON 对象:可以将另一个 JObject 作为值添加到现有的 JSON 对象中,形成嵌套结构。
  3. 转换为字符串:使用 ToString() 方法将 JObject 转换为 JSON 字符串。
  4. 解析 JSON 字符串:使用 JObject.Parse() 方法将 JSON 字符串解析为 JObject
  5. 访问属性:通过键名访问 JObject 中的值,并将其转换为相应的类型(如 stringintbool 等)。

上一篇:c# 数组添加元素

下一篇:c#字符串是否包含某个字符串

大家都在看

c# 二进制

c# 创建目录

c# socket服务端连接多个客户端

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

c# invoke方法

.net和c#

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站