今天以大家常用DLL'Newtonsoft.Json'为例给大家做个示范;
1、第一步新建项目
2、第二步,新建项目后,在窗体添加一个按钮Button和两个富文本框RichTextBox
3、第三步,VS->工具->NuGet包管理器->管理解决方案的NuGet 程序包->浏览->搜索(Newtonsoft)->安装第1个即可
4、第四步,在项目引用里面找到Newtonsoft引用然后把属性“复制到本地改为False”
5、第五步,在项目上面右击鼠标打开项目属性
6、第六步,在项目属性->资源->添加资源->添加现有文件;然后在项目目录packages->Newtonsoft.Json.13.0.1->lib->net45(根据项目框架选择)->Newtonsoft.Json.dll选择对应的dll文件添加到资源里面
7、第七步,编写测试代码
添加要格式化的json字符串
json格式化vb代码
''' <summary>
''' 格式化JSON字符串
''' </summary>
''' <param name='str'></param>
''' <returns></returns>
Private Function ConvertJsonString(str As String) As String
Dim serializer As New JsonSerializer()
Dim tr As TextReader = New StringReader(str)
Dim jtr As New JsonTextReader(tr)
Dim obj As Object = serializer.Deserialize(jtr)
If obj IsNot Nothing Then
Dim textWriter As New StringWriter()
Dim jsonWriter As New JsonTextWriter(textWriter) With {
.Formatting = Formatting.Indented,
.Indentation = 4,
.IndentChar = ' 'c
}
serializer.Serialize(jsonWriter, obj)
Return textWriter.ToString()
Else
Return str
End If
End Function
8、第八步,加载资源中DLL代码重点来咯
9、完整实现代码
Imports System.IO
Imports Newtonsoft.Json
Public Class Form1
Public Sub New()
''加载DLL到exe的事件
AddHandler AppDomain.CurrentDomain.AssemblyResolve, New ResolveEventHandler(AddressOf CurrentDomain_AssemblyResolve)
InitializeComponent()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
RichTextBox2.Text = ConvertJsonString(RichTextBox1.Text)
End Sub
''' <summary>
''' 把DLL加载到EXE中
''' </summary>
''' <param name='sender'></param>
''' <param name='args'></param>
''' <returns></returns>
Private Function CurrentDomain_AssemblyResolve(sender As Object, args As ResolveEventArgs) As System.Reflection.Assembly
Dim dllName As String = If(args.Name.Contains(','), args.Name.Substring(0, args.Name.IndexOf(','c)), args.Name.Replace('.dll', ''))
dllName = dllName.Replace('.', '_')
If dllName.EndsWith('_resources') Then
Return Nothing
End If
Dim rm As New System.Resources.ResourceManager([GetType].Namespace & '.Resources', System.Reflection.Assembly.GetExecutingAssembly())
Dim bytes As Byte() = DirectCast(rm.GetObject(dllName), Byte())
Return System.Reflection.Assembly.Load(bytes)
End Function
''' <summary>
''' 格式化JSON字符串
''' </summary>
''' <param name='str'></param>
''' <returns></returns>
Private Function ConvertJsonString(str As String) As String
Dim serializer As New JsonSerializer()
Dim tr As TextReader = New StringReader(str)
Dim jtr As New JsonTextReader(tr)
Dim obj As Object = serializer.Deserialize(jtr)
If obj IsNot Nothing Then
Dim textWriter As New StringWriter()
Dim jsonWriter As New JsonTextWriter(textWriter) With {
.Formatting = Formatting.Indented,
.Indentation = 4,
.IndentChar = ' 'c
}
serializer.Serialize(jsonWriter, obj)
Return textWriter.ToString()
Else
Return str
End If
End Function
End Class
联系客服