我正在尝试从用户发送到Web服务的查询中生成JSON输出(返回值)。
我目前用来执行此操作的代码(仅用于测试):
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim sqlSelect As String = "firstName, lastName, email" '3 field names to search by
Dim _count As Integer = 2 'Has 2 records returned
Dim _QueryData As New Dictionary(Of String, String)
Dim _Fields As String() = sqlSelect.Split(",")
For _int As Integer = 0 To _count - 1
For index As Integer = 0 To _Fields.Count - 1
_QueryData.Add(_Fields(index).Trim, "something" & index)
Next
Next
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(
_QueryData,
Formatting.Indented)
)
End Sub
现在我可以想到一个问题:
(1)使用词典我只限于一个“键”,所以一旦它再次为第二个记录循环,它将给出已经存在的“键”的错误。但是对于下一条记录没有相同的字段(“key”),它将不是JSON字符串......
如何修改代码以使其按照我需要的方式运行?
我可以像这样手动完成:
Dim sqlSelect As String = "firstName, lastName, email" '3 field names to search by
Dim _count As Integer = 2 'Has 2 records returned
Dim _QueryData As String = "{"
Dim _Fields As String() = sqlSelect.Split(",")
For _int As Integer = 0 To _count - 1
If _int >= 1 Then _QueryData &= "," & vbCrLf & "{" & vbCrLf
For index As Integer = 0 To _Fields.Count - 1
_QueryData &= """" & _Fields(index).Trim & """" & ":" & """" & "something" & index & """," & vbCrLf
Next
_QueryData = _QueryData.Substring(0, _QueryData.Length - 3) & vbCrLf & "}"
Next
产生:
{
"firstName":"something0",
"lastName":"something1",
"email":"something2"
},
{
"firstName":"something0",
"lastName":"something1",
"email":"something2"
}
答案 0 :(得分:1)
如果您正在执行查询,您应该能够将其读取到数据表,然后允许进行简单的序列化:
Dim sJSONObject As String
Dim sqlSelect As String = "firstName,lastName,email" '3 field names to search by
Dim _count As Integer = 2 'Has 2 records returned
Dim _QueryData As New DataTable()
Dim _Fields As String() = sqlSelect.Split(",")
Dim arrData As String()
For Each sFieldName In _Fields
_QueryData.Columns.Add(sFieldName)
Next
For _int As Integer = 0 To _count - 1
ReDim arrData(_Fields.Count - 1)
For index As Integer = 0 To _Fields.Count - 1
arrData(index) = "something" & index
Next
_QueryData.Rows.Add(arrData)
Next
sJSONObject = JsonConvert.SerializeObject(
_QueryData, Formatting.Indented)
这导致:
[{
"firstName": "something0",
"lastName": "something1",
"email": "something2"
},
{
"firstName": "something0",
"lastName": "something1",
"email": "something2"
}]
如果方形括号出现问题,请在发送
之前将其修剪掉