解析JSON/XML参数

问题描述:

这是一个快速和肮脏的POC我有其他有用的堆栈职位至今:解析JSON/XML参数

Public Function WebRequest(url As String) As String 
    Dim http As MSXML2.xmlhttp 
    Set http = CreateObject("MSXML2.ServerXMLHTTP") 

    http.open "GET", url, False 
    http.send 

    WebRequest = http.responseText 
    Set http = Nothing 
End Function 

Private Sub Command1_Click() 

Dim http As MSXML2.xmlhttp 
    Dim result As String 
    Dim url As String 
    Dim productId As String 

    productId = "2" 
    url = "http://localhost:1111/api/products/" & productId 
    result = WebRequest(url) 

    MsgBox result 

End Sub 

这需要一个简单的Web API和收益预期。响应内容如下:

{"Id":2,"Name":"Yo-yo","Category":"Toys","Price":3.75} 

将参数分配给变量以在应用程序的其余部分中使用的最佳方式是什么?

+0

为什么在这里使用'CreateObject()'而不是'New'? – Bob77

+0

@ Bob77我很快就复制了这个答案:https://*.com/a/27854657/7896203我从来没有使用VB6之前,所以我不能回答这个问题说实话。 – Reed

解析JSON没有“最好”的方法,但有几个现有的VB6类来这样做。 VB6或Windows中没有任何内容可以使用,所以没有任何明显的选择可以首先实现。

如果你不想使用现有的VB6类或第三方库,那么你可以“手动”使用自己的代码进行解析。只要你期望的JSON非常简单,可能就是你所需要的。

这里有很多陷阱,但它是否适合你的非常简单的例子,只要没有其他数据类型的使用,弦从来没有引号或转义符号等:

Option Explicit 

Private Sub Main() 
    Const SIMPLE_JSON As String = _ 
     "{""Id"":2,""Name"":""Yo-yo"",""Category"":""Toys"",""Price"":3.75}" 
    Dim JsonItems() As String 
    Dim Collection As Collection 
    Dim I As Long 
    Dim Parts() As String 
    Dim Value As Variant 

    JsonItems = Split(Mid$(SIMPLE_JSON, 2, Len(SIMPLE_JSON) - 2), ",") 
    Set Collection = New Collection 
    For I = 0 To UBound(JsonItems) 
     Parts = Split(JsonItems(I), ":") 
     Parts(0) = Mid$(Parts(0), 2, Len(Parts(0)) - 2) 
     If Left$(Parts(1), 1) = """" Then 
      Value = Mid$(Parts(1), 2, Len(Parts(1)) - 2) 
     Else 
      Value = Val(Parts(1)) 
     End If 
     Collection.Add Array(Parts(0), Value), Parts(0) 
    Next 

    With Collection 
     For I = 1 To .Count 
      Debug.Print .Item(I)(0); "="; .Item(I)(1) 
     Next 
    End With 
End Sub 

结果:

Id= 2 
Name=Yo-yo 
Category=Toys 
Price= 3.75 

Val()函数用于非字符串值,因为它是区域设置盲(始终使用不变的区域设置,应始终格式化JSON数字)。

+0

感谢您的帮助!我认为这不会很直接,但这是迄今为止我最好的资源!我将不得不进一步了解正在改进的传统服务中使用的数据类型。谢谢! – Reed