Ben*_*ack 39 vb6 serialization vba json web-services
我试图在VB6中使用Web服务.我控制的服务 - 当前可以返回SOAP/XML消息或JSON.我有一个非常困难的时候,如果VB6的SOAP类型(第1版)找出可以处理返回object
-而不是简单的类型,如string
,int
等.到目前为止,我想不出什么,我需要做的就是VB6而归玩对象.
所以我想我可能会将Web服务中的响应序列化为JSON字符串.VB6是否存在JSON解析器?
Ben*_*ack 41
查看JSON.org以获取许多不同语言的JSON解析器的最新列表(请参阅主页的底部).截至撰写本文时,您将看到两个不同JSON解析器的链接:
这个VB JSON库的实际语法非常简单:
Dim p As Object
Set p = JSON.parse(strFormattedJSON)
'Print the text of a nested property '
Debug.Print p.Item("AddressClassification").Item("Description")
'Print the text of a property within an array '
Debug.Print p.Item("Candidates")(4).Item("ZipCode")
Run Code Online (Sandbox Code Playgroud)Wol*_*ehn 14
以ozmike解决方案为基础,这对我不起作用(Excel 2013和IE10).原因是我无法在公开的JSON对象上调用方法.因此,它的方法现在通过附加到DOMElement的函数公开.不知道这是可能的(必须是IDispatch-thing),谢谢你.
正如ozmike所说,没有第三方库,只有30行代码.
Option Explicit
Public JSON As Object
Private ie As Object
Public Sub initJson()
Dim html As String
html = "<!DOCTYPE html><head><script>" & _
"Object.prototype.getItem=function( key ) { return this[key] }; " & _
"Object.prototype.setItem=function( key, value ) { this[key]=value }; " & _
"Object.prototype.getKeys=function( dummy ) { keys=[]; for (var key in this) if (typeof(this[key]) !== 'function') keys.push(key); return keys; }; " & _
"window.onload = function() { " & _
"document.body.parse = function(json) { return JSON.parse(json); }; " & _
"document.body.stringify = function(obj, space) { return JSON.stringify(obj, null, space); }" & _
"}" & _
"</script></head><html><body id='JSONElem'></body></html>"
Set ie = CreateObject("InternetExplorer.Application")
With ie
.navigate "about:blank"
Do While .Busy: DoEvents: Loop
Do While .readyState <> 4: DoEvents: Loop
.Visible = False
.document.Write html
.document.Close
End With
' This is the body element, we call it JSON:)
Set JSON = ie.document.getElementById("JSONElem")
End Sub
Public Function closeJSON()
ie.Quit
End Function
Run Code Online (Sandbox Code Playgroud)
以下测试从头开始构造JavaScript对象,然后对其进行字符串化.然后它将对象解析回来并迭代其键.
Sub testJson()
Call initJson
Dim jsObj As Object
Dim jsArray As Object
Debug.Print "Construction JS object ..."
Set jsObj = JSON.Parse("{}")
Call jsObj.setItem("a", 1)
Set jsArray = JSON.Parse("[]")
Call jsArray.setItem(0, 13)
Call jsArray.setItem(1, Math.Sqr(2))
Call jsArray.setItem(2, 15)
Call jsObj.setItem("b", jsArray)
Debug.Print "Object: " & JSON.stringify(jsObj, 4)
Debug.Print "Parsing JS object ..."
Set jsObj = JSON.Parse("{""a"":1,""b"":[13,1.4142135623730951,15]}")
Debug.Print "a: " & jsObj.getItem("a")
Set jsArray = jsObj.getItem("b")
Debug.Print "Length of b: " & jsArray.getItem("length")
Debug.Print "Second element of b: "; jsArray.getItem(1)
Debug.Print "Iterate over all keys ..."
Dim keys As Object
Set keys = jsObj.getKeys("all")
Dim i As Integer
For i = 0 To keys.getItem("length") - 1
Debug.Print keys.getItem(i) & ": " & jsObj.getItem(keys.getItem(i))
Next i
Call closeJSON
End Sub
Run Code Online (Sandbox Code Playgroud)
输出
Construction JS object ...
Object: {
"a": 1,
"b": [
13,
1.4142135623730951,
15
]
}
Parsing JS object ...
a: 1
Length of b: 3
Second element of b: 1,4142135623731
Iterate over all keys ...
a: 1
b: 13,1.4142135623730951,15
Run Code Online (Sandbox Code Playgroud)
由于 Json 只是字符串,因此如果我们能够以正确的方式操作它,无论结构多么复杂,它都可以轻松处理。我认为没有必要使用任何外部库或转换器来实现这一目的。这是我使用字符串操作解析 json 数据的示例。
Sub GetJsonContent()
Dim http As New XMLHTTP60, itm As Variant
With http
.Open "GET", "http://jsonplaceholder.typicode.com/users", False
.send
itm = Split(.responseText, "id"":")
End With
x = UBound(itm)
For y = 1 To x
Cells(y, 1) = Split(Split(itm(y), "name"": """)(1), """")(0)
Cells(y, 2) = Split(Split(itm(y), "username"": """)(1), """")(0)
Cells(y, 3) = Split(Split(itm(y), "email"": """)(1), """")(0)
Cells(y, 4) = Split(Split(itm(y), "street"": """)(1), """")(0)
Next y
End Sub
Run Code Online (Sandbox Code Playgroud)
更新:找到一种比使用Eval更安全的解析JSON的方法,这篇博文显示了Eval的危险... http://exceldevelopmentplatform.blogspot.com/2018/01/vba-parse-json-safer-with-jsonparse- and.html
迟到这个派对但对不起家伙,但到目前为止最简单的方法是使用Microsoft Script Control.一些使用VBA.CallByName钻取的示例代码
'Tools->References->
'Microsoft Script Control 1.0; {0E59F1D2-1FBE-11D0-8FF2-00A0D10038BC}; C:\Windows\SysWOW64\msscript.ocx
Private Sub TestJSONParsingWithCallByName()
Dim oScriptEngine As ScriptControl
Set oScriptEngine = New ScriptControl
oScriptEngine.Language = "JScript"
Dim sJsonString As String
sJsonString = "{'key1': 'value1' ,'key2': { 'key3': 'value3' } }"
Dim objJSON As Object
Set objJSON = oScriptEngine.Eval("(" + sJsonString + ")")
Debug.Assert VBA.CallByName(objJSON, "key1", VbGet) = "value1"
Debug.Assert VBA.CallByName(VBA.CallByName(objJSON, "key2", VbGet), "key3", VbGet) = "value3"
End Sub
Run Code Online (Sandbox Code Playgroud)
我实际上已经完成了一系列问答,探讨了与JSON/VBA相关的主题.
Q1 在Windows上的Excel VBA中,如何减轻由IDE的大小写行为破坏的解析JSON的点语法遍历问题?
Q2 在Windows上的Excel VBA中,如何循环解析JSON数组?
Q3 在Windows上的Excel VBA中,如何为已解析的JSON变量获取字符串化的JSON表示而不是"[object Object]"?
Q4 在Windows Excel VBA中,如何获取JSON键以抢占"运行时错误'438':对象不支持此属性或方法"?
Q5 在Windows上的Excel VBA中,对于已解析的JSON变量,这个JScriptTypeInfo究竟是什么?
归档时间: |
|
查看次数: |
82281 次 |
最近记录: |