从对象序列化到JSON

时间:2017-08-07 17:53:56

标签: json vb6

我在一些用VB6编写的遗留应用程序中使用Web服务。现在,我已经能够使用此处的VB JSON解析器解析从Web服务返回的JSON:http://www.ediy.co.nz/vbjson-json-parser-library-in-vb6-xidc55680.html

但是,我仍然硬编码传递给POST请求有效负载的JSON字符串。

一般来说:

result = WebRequestPost(url, "{""Id"":""" & productId & """,""Name"":""" & productName & """,""Category"":""" & productCat & """,""Price"":""" & productPrice & """}")

是否有更简洁的方法可以根据对象生成JSON有效负载?

1 个答案:

答案 0 :(得分:0)

我最终构建了自己的各种汇编程序......

Dim jsonArray() As String
'_______________________________________________________________
'Initializes the opening and closing braces of the JSON payload
Public Sub JSONInitialize()
ReDim jsonArray(1)
jsonArray(0) = "{"
jsonArray(1) = "}"
End Sub
'_______________________________________________________________
'Adds a string value to the JSON payload
Public Sub JSONAddString(nFieldName As String, nValue As String)
Dim temp As String
temp = jsonArray(UBound(jsonArray))

Dim index As Integer
index = UBound(jsonArray)

ReDim Preserve jsonArray(UBound(jsonArray) + 1)
jsonArray(UBound(jsonArray)) = temp
jsonArray(index) = """" & nFieldName & """:""" & nValue & ""","

End Sub
'_______________________________________________________________
'Adds an integer value to the JSON payload
Public Sub JSONAddInt(nFieldName As String, nValue As Integer)
Dim temp As String
temp = jsonArray(UBound(jsonArray))

Dim index As Integer
index = UBound(jsonArray)

ReDim Preserve jsonArray(UBound(jsonArray) + 1)
jsonArray(UBound(jsonArray)) = temp
jsonArray(index) = """" & nFieldName & """:" & nValue & ","

End Sub

所以(消毒)执行最终看起来像:

Dim o As New MyObject
Call o.JSONInitialize
Call o.JSONAddString("My JSON String Field", "Test String Value")
Call o.JSONAddInt("My JSON Int Field", 25)

o.JSONSerialize()返回:

{"My JSON String Field":"Test String Value","My JSON Int Field": 25,}

不幸的是,它将逗号放在最后,所以它不会赢得任何选美比赛,但我打电话的API并不关心。