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

界面如下:

测试结果:

相关推荐
mudtools14 小时前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
大飞pkz20 小时前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
唐青枫21 小时前
从入门到进阶:C#.NET Stopwatch 计时与性能测量全攻略
c#·.net
未来之窗软件服务1 天前
幽冥大陆(二)RDIFSDK 接口文档:布草洗涤厂高效运营的技术桥梁C#—东方仙盟
开发语言·c#·rdif·仙盟创梦ide·东方仙盟
1uther1 天前
Unity核心概念⑨:Screen
开发语言·游戏·unity·c#·游戏引擎
阿幸软件杂货间1 天前
Office转PDF转换器v1.0.py
开发语言·pdf·c#
sali-tec1 天前
C# 基于halcon的视觉工作流-章34-环状测量
开发语言·图像处理·算法·计算机视觉·c#
Tiger_shl1 天前
【层面一】C#语言基础和核心语法-02(反射/委托/事件)
开发语言·c#
Martin-Luo2 天前
Vue3 通过json配置生成查询表单
javascript·vue.js·json
星尘库2 天前
后端json数据反序列化枚举类型不匹配的错误
json