k3wise插件开发和调试过程中经常会遇到一些自定义的对象,如IDictionary、IVector、Recordset等,有的对象层层嵌套,而VB没有一个直观的方法查看这些对象的所有属性和值,就自己动手写了一个函数,代码如下,没怎么测试仅供参考
Public Function Object2Json(Optional ByVal vData As Variant) As String Dim sJson As StringDim vTemp As Variant On Error GoTo ErrL If InStr("String,Boolean,Date,Byte,Integer,Long,Double,Decimal", TypeName(vData)) > 0 Then sJson = "'" & Replace(CStr(vData), "'", "\'") & "'" ElseIf IsArray(vData) Then For vTemp = LBound(vData) To UBound(vData) sJson = sJson & Object2Json(vData(vTemp)) & "," Next sJson = IIf(Len(sJson) = 0, "[]", "[" & Mid(sJson, 1, Len(sJson) - 1) & "]") ElseIf TypeName(vData) = "IDictWord" Then sJson = vData.Name & ":" & Object2Json(vData.Value) ElseIf TypeName(vData) = "IDictionary" Then For Each vTemp In vData sJson = sJson & Object2Json(vTemp) & "," Next sJson = IIf(Len(sJson) = 0, "{}", "{" & Mid(sJson, 1, Len(sJson) - 1) & "}") ElseIf TypeName(vData) = "IVector" Then For vTemp = 1 To vData.Size sJson = sJson & Object2Json(vData.Item(vTemp)) & "," Next vTemp sJson = IIf(Len(sJson) = 0, "[]", "[" & Mid(sJson, 1, Len(sJson) - 1) & "]") ElseIf TypeName(vData) = "Recordset" Then vData.MoveFirst While Not vData.EOF sJson = sJson & "{" For vTemp = 0 To vData.Fields.Count - 1 sJson = sJson & vData.Fields(vTemp).Name & ":" & Object2Json(vData.Fields(vData.Fields(vTemp).Name).Value) & "," Next sJson = Mid(sJson, 1, Len(sJson) - 1) & "}," vData.MoveNext Wend sJson = IIf(Len(sJson) = 0, "[]", "[" & Mid(sJson, 1, Len(sJson) - 1) & "]") Else GoTo ErrL End If Object2Json = sJson Exit FunctionErrL: Object2Json = "'#" & TypeName(vData) & "#'"End Function