如何将JSON字符串正确解析为vb.net中的对象?既然我的JSON数据有[]这个括号,我认为它算作数组对吗?我无法更改JSON数据,因为我还有另一个应用程序使用该JSON。
这是我的JSON的样子:
[
{
"Id": "WEB1853257",
"Tgl_OPJ": "2018-10-31T08:32:14.223Z",
"Tgl_Jth_Tempo": "2018-11-07T08:25:14.436Z",
"Nm_Plg": "PURWACOKRO",
"Nm_Slsman": "BURHAN",
"Ket": "BARU",
"Divisi": "IPHONE X"
},
{
"Id": "WEB1853240",
"Tgl_OPJ": "2018-10-30T16:41:30.393Z",
"Tgl_Jth_Tempo": "2018-11-06T23:59:00.000Z",
"Nm_Plg": "PURWACOKRO",
"Nm_Slsman": "BURHAN",
"Ket": "SEKEN",
"Divisi": "IPHONE X"
},
{
"Id": "WEB1853238",
"Tgl_OPJ": "2018-10-30T16:28:43.416Z",
"Tgl_Jth_Tempo": "2018-11-06T23:59:00.000Z",
"Nm_Plg": "PURWACOKRO",
"Nm_Slsman": "BURHAN",
"Ket": "SEKEN",
"Divisi": "IPHONE XS"
}
]
这是我的vb.net代码:
Imports System.Net
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim url As String = String.Format("http://localhost:5000/phoneOrderList")
Dim serviceRequest As New WebClient
Dim response As String = serviceRequest.DownloadString(New Uri(url))
Dim a As PhoneOrderList = JsonConvert.DeserializeObject(Of PhoneOrderList)(response)
MessageBox.Show(a.Nm_Plg)
End Sub
End Class
Public Class PhoneOrderList
Public Property Id As String
Public Property Tgl_OPJ As String
Public Property Tgl_Jth_Tempo As String
Public Property Nm_Plg As String
Public Property Nm_Slsman As String
Public Property Ket As String
Public Property Divisi As String
End Class
当我单击按钮时,它给我这样的错误:
Newtonsoft.Json.JsonSerializationException:'无法反序列化 当前JSON数组(例如[1,2,3])转换为类型'WindowsApp2.OPJList' 因为该类型需要一个JSON对象(例如{“ name”:“ value”}) 正确反序列化。要解决此错误,请将JSON更改为 JSON对象(例如{“ name”:“ value”})或将反序列化类型更改为 实现集合接口的数组或类型(例如 ICollection,IList),例如可以从JSON反序列化的List 数组。还可以将JsonArrayAttribute添加到类型中以强制将其 从JSON数组反序列化。路径”,第1行,位置1。'
我已经将其更改为列表的数组类型,我错过了什么吗?
答案 0 :(得分:1)
您需要将JSON转换为PhoneOrderList的列表,而不是单个PhoneOrderList对象。所以...
Dim a = JsonConvert.DeserializeObject(Of List(Of PhoneOrderList))(response)
将正确地将JSON转换为PhoneOrderList对象的列表。使用上面的JSON,然后您应该看到a.Count
等于3,a(0).Id
等于“ WEB1853257”,a(1).Id
等于“ WEB1853240”,等等。