我尝试使用RestSharp(http://restsharp.org/)发布到一个安静的API
我的班级看起来像这样:
Public Class CreatePostcard
Public Property [to]() As [To]
Public Property front() As String
...
Public Class [to]
Public Property address_line1 As string
Public Property city As String
...
我的请求如下:
Dim request = New RestRequest("postcards", Method.POST)
Dim mm = New CreatePostcard() With {.description = "Test Desc",
.to = New [To]() With {.name = FirstName & " " & LastName, .address_line1 = Address1, .address_line2 = Address2, .address_city = City, .address_state = State, .address_zip = Zip},
.from = New From() With {.name = "TestFrom", .address_line1 = "123 Fake St", .address_city = "Bentonville", .address_state = "AK", .address_zip = "90210"},
.back = BackURL, .front = FrontURL, .message = ""}
request.AddObject(mm)
Dim response2 As IRestResponse(Of Postcard) = client.Execute(Of Postcard)(request)
API希望看起来像这样:
{
"description": "Demo Postcard job",
"to": {
"address_line1": "123 Test Street",
"address_city": "Mountain View",
"address_state": "CA",
"address_zip": "94041",
},
"from": {
"name": "Ami Wang",
"address_line1": "123 Test Avenue"
},
"message": null,
}
但我实际发送的是:
{
"to": "MyApp.To",
"from": "MyApp.From",
"front": "http://foo",
"back": "http://foo",
"message": "",
"description": "Test"
}
如何正确地对对象进行分类并将其发送到restful API?
答案 0 :(得分:0)
Visual Studio为json生成必要的类。在您的示例json中,只有一个标记实例“to”和“from”
尝试以下代码。我使用Nuget库中的Json.Net进行测试。
Private Sub TestJson()
Dim objFromJsonText As String = File.ReadAllText("C:\json.txt")
Dim obj As Rootobject
obj = JsonConvert.DeserializeObject(Of Rootobject)(objFromJsonText)
Dim jsonFromJsonObject = JsonConvert.SerializeObject(obj)
End Sub
Public Class Rootobject
Public Property description As String
Public Property [to] As [To]
Public Property from As From
Public Property message As Object
End Class
Public Class [To]
Public Property address_line1 As String
Public Property address_city As String
Public Property address_state As String
Public Property address_zip As String
End Class
Public Class From
Public Property name As String
Public Property address_line1 As String
End Class