购买域名和服务器多少钱,河北网络营销推广seo,10g免费空间申请,网站编辑超链接怎么做前言有时候#xff0c;我们需要将通过 WebAPI 接收 JSON 字符串转换成 C# 代码。Visual Studio 提供了一个功能菜单可以轻松实现#xff1a;执行完成后#xff0c;它会将生成的代码放在打开的的代码窗口中。但是#xff0c;如果有多个 JSON 字符串需要转换#xff0c;这个…前言有时候我们需要将通过 WebAPI 接收 JSON 字符串转换成 C# 代码。Visual Studio 提供了一个功能菜单可以轻松实现执行完成后它会将生成的代码放在打开的的代码窗口中。但是如果有多个 JSON 字符串需要转换这个过程非常繁琐而且容易出错。本文将介绍如何使用 Source Generator 将 JSON 字符串转换成 C# 类。实现原理解析 JSON 字符串首先我们需要解析 JSON 字符串分析它的结构再对应到 C# 类。这里我们使用 System.Text.Json 库。通过JsonDocument.Parse方法解析 JSON 字符串它将返回一个JsonDocument对象using var jsonDocument JsonDocument.Parse(json);下图很好的说明了JsonDocument的结构一个JsonDocument由多个JsonElement和JsonProperty组成一个JsonElement包含多个JsonProperty一个JsonProperty的值也是一个JsonElement。通过递归遍历我们可以解析出 JSON 字符串的结构。匹配 C# 类型接下来我们需要将解析出的 JSON 字符串结构匹配成 C# 类型。这里我们使用如下代码来存储类和属性信息public class ParsedType
{ //名称public string Name { get; private set; }//类型public TypeEnum Type { get; private set; }//针对 Array 的类型public ParsedType InternalType { get; private set; }//属性列表public IListPropertyInfo Properties { get; internal set; }//是否是顶级类用于区分嵌套子类public bool IsRoot { get; internal set; }
}public class PropertyInfo
{public string Name { get; private set; }public string JsonName { get; private set; }public ParsedType Type { get; private set; }
}生成 C# 类代码匹配出了 C# 类型生成 C# 类代码就非常容易了。这里我们使用如下代码WriteFileStart(sw,name_space,class_name);foreach (var type in types)
{WriteClass(sw, type);
}WriteFileEnd(sw);types是上一步解析出的 ParsedType 集合。Source Generator现在我们需要使用 Source Generator 将完整流程实现。首先我们定义了一个 Attributeconst string attributeText using System;namespace MyIO
{[AttributeUsage(AttributeTargets.Class)]public sealed class ParseJsonAsClassAttribute : Attribute{public ParseJsonAsClassAttribute(string fileName){FileName fileName;}public string FileName { get; set; }}
}
;context.AddSource(MyIO.ParseJsonAsClassAttribute.g, SourceText.From(attributeText, System.Text.Encoding.UTF8));然后我们遍历项目中所有声明了ParseJsonAsClassAttribute的类拿到namesapce、classname和 JSON 字符串生成 C# 类代码然后写到项目中foreach (var memberSyntax in memberSyntaxes)
{if (memberSyntax is ClassDeclarationSyntax classDeclarationSyntax){var name_space GetNamespace(classDeclarationSyntax);var class_name classDeclarationSyntax.Identifier.ValueText;string json GetJson(classDeclarationSyntax);if (json null){continue;}var sourceText GenerateSource(name_space, class_name, json);if (sourceText ! null){this.context.AddSource(MyIO.ParseJsonAsClass. classDeclarationSyntax.Identifier.ValueText .g, sourceText);}}this.context.CancellationToken.ThrowIfCancellationRequested();
}使用在项目中安装 NuGet 包dotnet add package MyIO.ParseJsonAsClass.SourceGenerator在项目中添加一个 JSON 文件{code: 200,msg: ok,obj:{a:1,subObj:{a:1}},data: [1,2],array: [{a:1.0},{a:null}]
}在项目中添加一个 C# 文件using MyIO;
namespace ConsoleApp1
{[ParseJsonAsClass(sample.txt)]internal partial class Class1{ }
}sample.txt 是上一步中添加的 JSON 文件的名称。编译项目总结相关源代码已上传到 GitHub: https://github.com/feiyun0112/MyIO.ParseJsonAsClass.SourceGenerator点击“阅读原文”可直达欢迎 Star。添加微信号【MyIO666】邀你加入技术交流群