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; }
    } 
     
}

界面如下:

测试结果:

相关推荐
亚洲小炫风42 分钟前
flutter json解析增强
flutter·json·json兼容格式
云草桑1 小时前
基于.NET后端实现图片搜索图片库 核心是计算上传图片与库中图片的特征向量相似度并排序展示结果
图像处理·microsoft·c#·.net
o0向阳而生0o1 小时前
20、.NET SDK概述
c#·.net
逍遥德2 小时前
前端工程化-包管理NPM-package.json 和 package-lock.json 详解
前端·npm·json
BruceNeter2 小时前
WinDebug查看C#程序运行内存中的数据库连接字符串
c#·windebug
Wythzhfrey4 小时前
单片机Day05---静态数码管
c语言·单片机·嵌入式硬件·学习·c#·51单片机
夜月yeyue6 小时前
STM32启动流程详解
linux·c++·stm32·单片机·嵌入式硬件·c#
码观天工6 小时前
解锁.NET 9性能优化黑科技:从内存管理到Web性能的最全指南
性能优化·c#·.net·内存管理·异步·.net 9
Tdm_8887 小时前
SQL Server中OPENJSON + WITH 来解析JSON
java·数据库·sql·c#·json·mssql
观无10 小时前
关于Newtonsoft.Json
c#