3

I know it's possible to use a library like VBAJSON to convert an array or a dictionary to json, but not a custom class instance in office 2013.

Searching turns up no libraries for handling objects to json, so I figure there must be some other way.

So, I'm wondering:

  • is it possible for an object to be recursively converted to a dictionary so the to-json conversion can then happen, without having to write a lengthy custom "ToDictionary" method for each class?

  • is there another way (other than not using objects) that json output can be reached from custom class objects?

    At the moment, I've written ToDictionary methods for each class to output the instance as a dictionary. It's messy, but gets the job done.

6
  • I came across this recently but have not gone further than cursory review. At a glance, though, it looks like it may be what you're looking for. Commented Oct 11, 2015 at 0:50
  • I saw it too, from what I could see, it uses a custom "object" CObject or such that is essentially a dictionary which is fed to the json conversion function Commented Oct 11, 2015 at 1:24
  • Hmmm ok I looked a little closer (but still not close enough) my first impression was that it was a generic Stringify function, but now I think maybe it's specific only to the one particular Class. Commented Oct 11, 2015 at 12:56
  • One idea, not always ideal, would be to use JSON or XML representation of your data instead of VBA class object. Commented Oct 11, 2015 at 12:58
  • I can't think of a situation where that's ever ideal. Objects are far more flexible than json data Commented Oct 11, 2015 at 17:48

3 Answers 3

15

It's an old question, but without an answer, so let me try to answer with code.

I built a function to convert VBA structure (using Dictionary) to JSON. This function accepts nested object (nested Dictionary):

Function ToJson(ByVal dict As Object) As String
    Dim key As Variant, result As String, value As String

    result = "{"
    For Each key In dict.Keys
        result = result & IIf(Len(result) > 1, ",", "")

        If TypeName(dict(key)) = "Dictionary" Then
            value = ToJson(dict(key))
            ToJson = value
        Else
            value = """" & dict(key) & """"
        End If

        result = result & """" & key & """:" & value & ""
    Next key
    result = result & "}"

    ToJson = result
End Function

Test:

Sub MyTest()
    Dim body As String
    Set dictSubValues = CreateObject("Scripting.Dictionary")
    Set dictBody = CreateObject("Scripting.Dictionary")

    dictSubValues.Add "SubValue1", "2.1"
    dictSubValues.Add "SubValue2", "2.2"

    dictBody.Add "Value1", "1"
    dictBody.Add "Value2", dictSubValues

    body = ToJson(dictBody)
    Debug.Print (body)
End Sub

Output:

{
   "Value1":"1",
   "Value2":{
      "SubValue1":"2.1",
      "SubValue2":"2.2"
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

For handling double quotes in the value, a simple Replace is enough. value = """" & Replace(dict(key), """", "\""") & """" For a complete solution, replace also `vbBack->\b; vbCr->\r; vbLf->\n; vbTab->\t; \->\`
1

When I first started to write this question I was positvely stuck. Then I had a lightbulb moment to write a ToDictionary method for the class to convert the object to a dictionary how I want it.

So something like:

public function ToDictionary() as string
    dim d as dictionary
    set d = new dictionary
    d.add "id" Me!id
    d.add "title" Me!title
    ...
    Set ToDictionary = d
    set d = Nothing
end function

Comments

0

You can serialize the object to XML and from there it would be easier to convert to JSON and there are many posts online on how to do it.

Note however that converting XML to JSON isn't as trivial as it sounds and there are many pitfalls that you should be aware of.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.