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

界面如下:

测试结果:

相关推荐
子正7 分钟前
C环境下更简洁的cJSON辅助函数
json
远方16095 小时前
18-Oracle 23ai JSON二元性颠覆传统
数据库·oracle·json
程序猿小D7 小时前
第22节 Node.js JXcore 打包
开发语言·人工智能·vscode·node.js·c#
飞由于度8 小时前
C#中清空DataGridView的方法
开发语言·c#
大熊程序猿9 小时前
《开篇:课程目录》
前端·c#
周杰伦fans9 小时前
C#中用于控制自定义特性(Attribute)
后端·c#
nuclear201111 小时前
使用 C# 将 Word、Excel、PDF 和 PPT文档转换为 Markdown 格式
c#·word转markdown·pdf转markdown·excel转markdown·ppt转markdown·doc转markdown·docx转markdown
深圳视觉软件JJ12 小时前
wpf在image控件上快速显示内存图像
c#
浮生若梦l13 小时前
在 Spring Boot 项目里,MYSQL中json类型字段使用
spring boot·mysql·json
henreash16 小时前
C# dll版本冲突解决方案
开发语言·c#