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

界面如下:

测试结果:

相关推荐
future14121 小时前
游戏开发日记
数据结构·学习·c#
军训猫猫头3 小时前
3.检查函数 if (!CheckStart()) return 的妙用 C#例子
开发语言·c#
yngsqq6 小时前
netdxf—— CAD c#二次开发之(netDxf 处理 DXF 文件)
java·前端·c#
每日出拳老爷子6 小时前
[WinForms] 如何为 .NET Framework 4.8 窗体程序添加自定义图标
visualstudio·c#·.net
wtsolutions8 小时前
Excel to JSON API by WTSolution Documentation
json·excel·api·wtsolutions
钢铁男儿13 小时前
C#接口实现详解:从理论到实践,掌握面向对象编程的核心技巧
java·前端·c#
神所夸赞的夏天14 小时前
c#获取Datatable中某列最大或最小的行数据方法
开发语言·c#
我是唐青枫14 小时前
C#.NET serilog 详解
开发语言·c#·.net
future141215 小时前
项目开发日记
前端·学习·c#·游戏开发
我是苏苏1 天前
C#基础:Winform桌面开发中窗体之间的数据传递
开发语言·c#