C#解析JSON的常用库--Newtonsoft.Json

一、库介绍

在C#中,解析JSON的常用库有Newtonsoft.Json (也称为Json.NET )和 System.Text.Json (从 .NET Core 3.0 开始引入)。本文主要介绍 Newtonsoft.Json

二、下载

官网:

https://www.nuget.org/packages/Newtonsoft.Json/

https://www.newtonsoft.com/json

选择下载

选择 Releases ,选择合适的版本下载即可。

三、工程配置

工程添加 json 的 dll 动态库。

先解压下载的压缩包,选择合适的 dll 动态库文件。


将 dll 动态库 复制到工程中,工程添加 dll 动态库。

选择 添加引用

选择 dll 动态库:

代码中引用

using Newtonsoft.Json; 

四、测试代码

测试代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Newtonsoft.Json;  

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        /*
        public class Person  
        {  
            public string Name { get; set; }  
            public int Age { get; set; }  
        } 
        */
        private void button1_Click(object sender, EventArgs e)
        {
            jsonTest();
        }
        private void jsonTest()
        {
            string json = "{\"Name\":\"John Doe\",\"Age\":30}";
            Console.WriteLine(json); // 输出: {"Name":"John Doe","Age":30} 
  
            // 序列化对象到JSON字符串  
            string jsonSerialized = JsonConvert.SerializeObject(new Person { Name = "John Doe2", Age = 18 });  
            Console.WriteLine(jsonSerialized); // 输出: {"Name":"John Doe2","Age":18}  
  
            // 从JSON字符串反序列化到对象  
            Person person = JsonConvert.DeserializeObject<Person>(json);  
            Console.WriteLine("Name:"+person.Name + "Age:"+person.Age); // 输出: Name: John Doe, Age: 30  

            Person person2 = JsonConvert.DeserializeObject<Person>(jsonSerialized);
            Console.WriteLine("Name:" + person2.Name + "Age:" + person2.Age); // 输出: Name: John Doe2, Age: 18  
        }

    }
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    } 
     
}

界面如下:

测试结果:

相关推荐
HH牛码2 小时前
C# 中 Array、ArrayList 和 List 的比较
开发语言·c#
HH牛码2 小时前
C#学生管理系统 进阶(通过接口,继承接口的类,实现接口约束_对List中存储的数据进行排列)
c#
吾与谁归in3 小时前
C#实现本地Deepseek模型及其他模型的对话
人工智能·c#·wpf·deepseek
子蛟7 小时前
Get a free SSL certificate interface.
c#·ssl
一只蜗牛儿11 小时前
C# 版 OpenCV:OpenCVSharp 最详细最全面教程(万字详细总结)
开发语言·opencv·c#
学海无涯,行者无疆11 小时前
使用Jenkins实现Windows服务器下C#应用程序发布
windows·c#·jenkins·.net·cicd·自动发布·一键发布
正宗咸豆花12 小时前
【PromptCoder】使用 package.json 生成 cursorrules
人工智能·json·prompt·个人开发
tnnnnt13 小时前
今天锐评一下C#
开发语言·c#
Sator114 小时前
C#与AI的交互(以DeepSeek为例)
ai·语言模型·c#
sinat_3198680715 小时前
Spring Boot2.0之十 使用自定义注解、Json序列化器实现自动转换字典类型字段
spring boot·后端·json