Visual Studio 从普通字符串构建JSON字符串

cxfofazt  于 2023-03-19  发布在  其他
关注(0)|答案(2)|浏览(203)

我一直在尝试将JSON字符串导入VB .NET,只是为了试验我正在使用的HTTP客户端,这是一个一次性的练习,但它将允许我确认一些令人费解的功能,我正在体验。JSON是:

{
 "BoundaryType": "Outside",
 "StartTime": "2022-12-07T00:00:00",
 "EndTime": "2022-12-08T00:00:00",
 "TagFilter": "atagname",
 "Delimiter":"",
 "ServerName": "aservername"
 }

尝试在VB .NET中将其复制为纯字符串被证明是一个RPITA。无论我做什么,VB .NET似乎不希望允许我连接一个单双引号。我甚至采取了改变JSON,用“!”作为占位符来取代双引号,然后用双引号替换,如下所示:

{
 !BoundaryType!: !Outside!,
 !StartTime!: !2022-12-07T00:00:00!,
 !EndTime!: !2022-12-08T00:00:00!,
 !TagFilter!: !atagname!,
 !Delimiter!:!!,
 !ServerName!: !aservername!
 }

 content = content.Replace("!", Chr(34))

但这仍然会导致:

{
 ""BoundaryType"": ""Outside"",
 ""StartTime"": ""2022-12-07T00:00:00"",
 ""EndTime"": ""2022-12-08T00:00:00"",
 ""TagFilter"": ""atagname"",
 ""Delimiter"":"""",
 ""ServerName"": ""aservername""
 }

奇怪的是,如果我在Visual Studio中的文本可视化工具中查看它,它会显示我想要的内容:

{
"BoundaryType": "Outside",
"StartTime": "2022-12-07T00:00:00",
"EndTime": "2022-12-08T00:00:00",
"TagFilter": "atagname",
"Delimiter":"",
"ServerName": "aservername"
}

但是作为变量传递到函数中,我得到了重复的双引号。

5ssjco0h

5ssjco0h1#

使用“”在字符串中插入双引号:

Dim json As String = "{" & vbCrLf & """BoundaryType"":  ""Outside""" & vbCrLf & "}"
MsgBox(json)
31moq8wy

31moq8wy2#

如果要完全避免此问题,可以使用标记来定义字符串:
代码:

Dim JsonData = <json> 
        {
            "BoundaryType": "Outside",
            "StartTime": "2022-12-07T00:00:00",
            "EndTime": "2022-12-08T00:00:00",
            "TagFilter": "atagname",
            "Delimiter":"",
            "ServerName": "aservername"
        }
    </json>

    Dim results = Newtonsoft.Json.JsonConvert.DeserializeObject(Of JsonExample)(JsonData)

    MsgBox(results.BoundaryType)

类别:

Public Class JsonExample
    Public Property BoundaryType As String
    Public Property StartTime As DateTime
    Public Property EndTime As DateTime
    Public Property TagFilter As String
    Public Property Delimiter As String
    Public Property ServerName As String
End Class

相关问题