我尝试使用Json.net将Application Insights Analytics(AIA)中的JSON反序列化到我的班级。我不确定我是否正确接近它,但是我使用LINQ-to-JSON来获取JSON的数据部分,然后尝试使用以下代码反序列化到我的类:
Dim rawjson As String = GetTelemetry()
Dim o As JObject = JObject.Parse(rawjson)
Dim ds = DirectCast(o("Tables")(0)("Rows"), JArray)
Dim Sessions As List(Of Session) = JsonConvert.DeserializeObject(Of List(Of Session))(ds)
这失败了,因为来自AIA的JSON采用以下格式:
"Rows": [
[
"Boy",
"9",
"",
"",
"0",
"0",
"22",
"0"
],
[
"Boy",
"9",
"",
"",
"0",
"0",
"41",
"0"
],
请注意,各行的数据是数组而不是对象。
我的Session
类的定义如下:
Public Class Session
Public Property Gender As String
Public Property Age As Integer
Public Property SessionVids As Integer
Public Property TotalVids As Integer
Public Property ChildUse As Integer
Public Property ChildTime As Integer
Public Property AdultUse As Integer
Public Property AdultTime
End Class
有人可以解释一下如何做到这一点吗?
答案 0 :(得分:0)
您可以将JArray
行(ds
)转换为Session
个对象列表,如下所示:
Dim Sessions As List(Of Session) =
ds.Select(Function(ja)
Dim s As New Session()
s.Gender = ja(0).Value(Of String)()
s.Age = GetInt(ja(1))
s.SessionVids = GetInt(ja(2))
s.TotalVids = GetInt(ja(3))
s.ChildUse = GetInt(ja(4))
s.ChildTime = GetInt(ja(5))
s.AdultUse = GetInt(ja(6))
s.AdultTime = GetInt(ja(7))
Return s
End Function).ToList()
其中GetInt
是一个如下定义的辅助函数:
Public Function GetInt(jt As JToken) As Integer
Dim i As Integer
If Integer.TryParse(jt.Value(Of String)(), i)
Return i
End If
Return 0
End Function
需要辅助函数,因为当您的类需要有效的整数时,JSON的某些值为空字符串。