【发布时间】:2021-02-10 03:06:20
【问题描述】:
我想使用 Newtonsoft 反序列化集合将 JSON 引号字符串转换为引号列表。
我在尝试转换时遇到错误:
无法从 System.String 转换或转换为 System.Collections.Generic.List`1[System.String]。
然后我尝试将图像属性更改为:
Private _images As String()
Public Property images() As String()
Get
Return _images
End Get
Set(ByVal value As String())
_images = value
End Set
End Property
然后我得到错误:
无法从 System.String 转换或转换为 System.String[]。
如何将我的 JSON 转换为我的类,这样我不仅拥有作者和引号字符串属性,而且还有图像数组作为强类型?
Public Class quote
Private _author As String
Public Property author() As String
Get
Return _author
End Get
Set(ByVal value As String)
_author = value
End Set
End Property
Private _quote As String
Public Property quote() As String
Get
Return _quote
End Get
Set(ByVal value As String)
_quote = value
End Set
End Property
End Class
Dim quotesString As String = "[{""author"": ""J.K. Rowling"",""quote"": ""\u201cThe truth.\"" Dumbledore sighed. \""It is a beautiful and terrible thing, and should therefore be treated with great caution.\u201d"",""images"": [""dumbledore1.jpg"", ""dumbledore2.jpg"", ""dumbledore3.jpg""]}, {""author"": ""Jimi Hendrix"",""quote"": ""\u201cI'm the one that's got to die when it's time for me to die, so let me live my life the way I want to.\u201d"",""images"": [""Jimi.jpg"",""Jimi3.jpg"",""Jimi2.jpg""]},{""author"": ""J.M. Barrie"",""quote"": ""\u201cTo die will be an awfully big adventure.\u201d"",""images"": [""Barrie.jpg"",""Barrie1.jpg"",""Barrie2.jpg""]}]"
Dim quotes As List(Of quote) = Newtonsoft.Json.JsonConvert.DeserializeObject(Of List(Of quote))(quotesString)
JSON 源
[{
"author": "J.K. Rowling",
"quote": "\u201cThe truth.\" Dumbledore sighed. \"It is a beautiful and terrible thing, and should therefore be treated with great caution.\u201d",
"images": ["dumbledore1.jpg", "dumbledore2.jpg", "dumbledore3.jpg"]
}, {
"author": "Jimi Hendrix",
"quote": "\u201cI'm the one that's got to die when it's time for me to die, so let me live my life the way I want to.\u201d",
"images": ["Jimi.jpg","Jimi3.jpg","Jimi2.jpg"]
},
{
"author": "J.M. Barrie",
"quote": "\u201cTo die will be an awfully big adventure.\u201d",
"images": ["Barrie.jpg","Barrie1.jpg","Barrie2.jpg"]
}
]
【问题讨论】:
-
images属性的内容不是有效的 JSON,因此您不能以这种方式对其进行反序列化。您需要使用正则表达式(或String.Split在紧要关头)提取值。 -
@Dai 谢谢,我自己控制 JSON 源,所以我现在更新它。你能帮忙吗?
-
另外,您使用 VB.NET 有什么原因吗?
-
是的,正在处理遗留项目
-
你有我的同情。他们强迫你使用什么版本的 VB.NET?
标签: arrays json vb.net class json.net