如何将数组/集合添加到VBA POST JSON

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何将数组/集合添加到VBA POST JSON相关的知识,希望对你有一定的参考价值。

我已经成功地在https://github.com/VBA-tools/VBA-Web中实现了VBA-Web代码,但是我不知道如何将带有数组或集合的项添加到主体中。对于使用数组或集合,我是一个新手。这是我要发布的Json数据:

{
  "operation": "CREATE",
  "orderNo": "ORD001",
  "type": "D",
  "date": "2014-10-14",
  "location": {
    "address": "393 Hanover St, Boston, MA 02113, USA",
    "locationNo": "LOC001",
    "locationName": "Green Cross Pharmacy North End",
    "acceptPartialMatch": true
  },
  "duration": 20,
  "twFrom": "10:00",
  "twTo": "10:59",
  "load1": 10,
  "load2": 25,
  "vehicleFeatures": ["FR"],
  "skills": ["SK001", "SK002"],
  "notes": "Deliver at back door"
}

如何将位置数据添加到此代码中以进行发布?

Sub PostMan()
Dim Body As New Dictionary
Body.Add "operation", "CREATE"
Body.Add "orderNo", "ORD101"
Body.Add "type", "D"
Body.Add "date", "2020-04-24"
Body.Add "location", 'How do I the location data here? 
Body.Add  "vehicleFeatures", 'How do I add this item?
Body.Add  "skills", 'How do I add this item?

Dim Client As New WebClient
Dim Response As WebResponse
Set Response = Client.PostJson("https://api.optimoroute.com/v1/create_order?key=AUTH_KEY", Body)

Worksheets("Open1").Range("A1").Value = Response.Content
End Sub
答案

对于我的大部分JSON工作,我都使用JsonConverter中的this repository。我创建了关于如何在this answer中构造JSON对象的有用参考。根据该结构,您可以将位置添加为Dictionary,将数组添加为Collections

我使用JsonConverter审查并验证了JSON输出,但未在您的网站上对其进行测试。

Option Explicit

Sub PostMan()
    Dim Body As New Dictionary
    Body.Add "operation", "CREATE"
    Body.Add "orderNo", "ORD101"
    Body.Add "type", "D"
    Body.Add "date", "2020-04-24"

    Dim location As Dictionary
    Set location = New Dictionary
    With location
        .Add "address", "393 Hanover St, Boston, MA 02113, USA"
        .Add "locationNo", "LOC001"
        .Add "locationName", "Green Cross Pharmacy North End"
        .Add "acceptPartialMatch", True
    End With
    Body.Add "location", location

    Dim features As Collection
    Set features = New Collection
    features.Add "FR"
    Body.Add "vehicleFeatures", features

    Dim skills As Collection
    Set skills = New Collection
    With skills
        .Add "SK001"
        .Add "SK002"
    End With
    Body.Add "skills", skills

    Dim json As String
    json = JsonConverter.ConvertToJson(Body, Whitespace:=" ")

    Debug.Print json

'    Dim Client As New WebClient
'    Dim Response As WebResponse
'    Set Response = Client.PostJson("https://api.optimoroute.com/v1/create_order?key=AUTH_KEY", Body)
'
'    Worksheets("Open1").Range("A1").Value = Response.Content
End Sub

以上是关于如何将数组/集合添加到VBA POST JSON的主要内容,如果未能解决你的问题,请参考以下文章

如何将项目添加到 json 文件格式化数组

如何在VBA中加入集合

如何将 JSON 数组保存到 mongodb 集合中

为啥我无法使用 MSXML2 和 VBA 将 HTML 类名添加到元素集合

如何将多维数组添加到序列化的 POST 数据中?

怎么将json对象添加进json数组中