如何将数组/集合添加到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的主要内容,如果未能解决你的问题,请参考以下文章