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

c# string 转json

作者:紛手也是一茽の媄丽   发布日期:2026-06-17   浏览:128

using System;
using System.Text.Json;

class Program
{
    static void Main()
    {
        // 定义一个字符串,表示JSON格式的数据
        string jsonString = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";

        // 将 JSON 字符串反序列化为对象
        Person person = JsonSerializer.Deserialize<Person>(jsonString);

        // 输出对象的属性值
        Console.WriteLine($"Name: {person.Name}, Age: {person.Age}, City: {person.City}");

        // 将对象序列化为 JSON 字符串
        string newJsonString = JsonSerializer.Serialize(person);

        // 输出新的 JSON 字符串
        Console.WriteLine(newJsonString);
    }
}

// 定义一个类来匹配 JSON 数据结构
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string City { get; set; }
}

解释说明:

  1. 定义 JSON 字符串:我们首先定义了一个表示 JSON 数据的字符串 jsonString
  2. 反序列化:使用 JsonSerializer.Deserialize<Person>(jsonString) 方法将 JSON 字符串转换为 Person 类的对象。
  3. 输出对象属性:通过访问 person 对象的属性,输出其内容。
  4. 序列化:使用 JsonSerializer.Serialize(person) 方法将 Person 对象转换回 JSON 字符串。
  5. 输出新的 JSON 字符串:最后,输出新生成的 JSON 字符串。

这段代码展示了如何在 C# 中使用 System.Text.Json 命名空间中的 JsonSerializer 类进行 JSON 和对象之间的转换。

上一篇:c# 获取文件路径

下一篇:c# list foreach

大家都在看

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 中文站