提问人:Gabriele Cozzolino 提问时间:7/28/2023 最后编辑:Gabriele Cozzolino 更新时间:7/31/2023 访问量:32
VB.NET 如何处理格式奇怪的 json
VB.NET how to handle a json oddly formatted
问:
我有这个json:
POST /API/AlarmEvent/EventPush HTTP/1.1
Host: 192.168.2.103:123
Accept: */*
Content-Type: application/json;charset=UTF-8
Content-Length: 112652
{"result":"success","data":{"EventType":"LPD","EventTime":"2015-1-19 4:33:4","EventAction":"start","ChannelName":"PERGENOVA","DeviceName":"BS-IPT4704G3MZ+","IPAddress":"192.168.2.168","MacAddress":"00-23-63-92-25-47","PicData":{"PlateInfo":[{"Id":"","GrpId":3,"SnapId":"AH234MG","Type":10,"StrChn":"CH1","StartTime":1421641983,"EndTime":1421641987,"Chn":0,"Sex":0,"PlateColor":0,"CarBrand":"","CarType":"","Owner":"","IdCode":"","Job":"","Phone":"","Domicile":"","Remark":"","PlateImg":"/9j/4AAQSkZJRgABAQIAdgB2AAD/7wAPAAAAAAAAAAAAAAAAAP/bAEMAAwICAwICAwMDAwQDAwQFCAUFBAQFCgcHBggMCgwMC...=="}]}}}
注意:为了可读性,我截断了 PlateImg 数据,因为它是 100k 字节>字符串。
只反序列化 json 数据而忽略第一部分的最佳实践是什么?
POST /API/AlarmEvent/EventPush HTTP/1.1
Host: 192.168.2.103:123
Accept: */*
Content-Type: application/json;charset=UTF-8
Content-Length: 112652
我这样做了,它正在工作,但我觉得它很丑:
text = text.Split(vbLf)(6).ToString
编辑: 下面是 tcp 侦听器的代码
Dim _server As TcpListener
Sub tcpListenerINIT()
Try
Dim ip As String = My.Settings.tcpListenerIP
Dim port As Integer = My.Settings.tcpListenerPort
_server = New TcpListener(IPAddress.Parse(ip), port)
_server.Start()
Threading.ThreadPool.QueueUserWorkItem(AddressOf NewClient)
Catch ex As Exception
Console.WriteLine(ex)
End Try
End Sub
Private Sub NewClient(state As Object)
Try
Using client As TcpClient = _server.AcceptTcpClient()
Threading.ThreadPool.QueueUserWorkItem(AddressOf NewClient)
Using ns As NetworkStream = client.GetStream()
Dim buffer As New MemoryStream() ' Use MemoryStream as a dynamic buffer
Dim bytesRead As Integer
Dim receiveBuffer(4096) As Byte ' Buffer to read incoming data in chunks
Do
bytesRead = ns.Read(receiveBuffer, 0, receiveBuffer.Length)
If bytesRead > 0 Then
buffer.Write(receiveBuffer, 0, bytesRead)
End If
Loop While bytesRead > 0
buffer.Seek(0, SeekOrigin.Begin) ' Reset the position of the MemoryStream
Dim receivedData(buffer.Length) As Byte
buffer.Read(receivedData, 0, receivedData.Length)
' Now you have the complete message in the receivedData array as bytes.
If receivedData.Length > My.Settings.minLenghtForSuccess Then
Dim text As String = Encoding.UTF8.GetString(receivedData)
[CODE]
End If
End Using
End Using
Catch ex As Exception
End Try
End sub
答: 暂无答案
评论
Catch ex As Exception