在反序列化某些JSON并尝试访问root.items后,我收到以下错误:
root.items.Count |> should equal 2
System.NullReferenceException: 'Object reference 未设置为 对象的实例。
root.items@为空。
JSON 如下所示:
{
"items": [
{
"snippet": {
"title": "Nikeza: F# Backwards Pipe Operator",
"tags": [
"Elm",
"F#",
"Giraffe",
"Functional Programming",
"Software Development"
]
}
},
{
"snippet": {
"title": "Giraffe: VS Code bug that doesn't show up in VS 20017 (3)",
"tags": [
"Hangouts On Air",
]
}
},
{
"snippet": {
"title": "Software Craftsmanship Conference - London",
"tags": [
"Programming",
"Software Development",
]
}
}
]
}
这是我的代码:
[<CLIMutable>]
type Snippet = { title: string; tags: Collections.Generic.List<String> }
[<CLIMutable>]
type Item = { snippet : Snippet }
[<CLIMutable>]
type Response = { items : Collections.Generic.List<Item> }
[<Test>]
let ``Apply tags to videos`` () =
let delimitedIds = ["id1";"id2";"id3"] |> String.concat ","
let url = String.Format(requestTagsUrl, apiKey, delimitedIds)
let response = httpClient.GetAsync(url) |> Async.AwaitTask |> Async.RunSynchronously
if response.IsSuccessStatusCode
then let root = response.Content.ReadAsAsync<Response>() |> Async.AwaitTask |> Async.RunSynchronously
root.items.Count |> should equal 2
else Assert.Fail()
我刚刚为它写了一个测试,我可以确认它的反序列化部分是正确的。检查请求是否正确返回响应。
open System
open Expecto
let json =
"""
{
"items": [
{
"snippet": {
"title": "Nikeza: F# Backwards Pipe Operator",
"tags": [
"Elm",
"F#",
"Giraffe",
"Functional Programming",
"Software Development"
]
}
},
{
"snippet": {
"title": "Giraffe: VS Code bug that doesn't show up in VS 20017 (3)",
"tags": [
"Hangouts On Air",
]
}
},
{
"snippet": {
"title": "Software Craftsmanship Conference - London",
"tags": [
"Programming",
"Software Development",
]
}
}
]
}
"""
[<CLIMutable>]
type Snippet = { title: string; tags: Collections.Generic.List<String> }
[<CLIMutable>]
type Item = { snippet : Snippet }
[<CLIMutable>]
type Response = { items : Collections.Generic.List<Item> }
[<Tests>]
let tests =
testList "Test" [
test "Testing deserialization" {
let result : Response = Json.deserialize json
Expect.equal result.items.Count 3 "Should have 3 items"
}
]
以下内容对我有用:
总之,我不得不使用以下方法检索实际的 json 字符串:
json = response.Content.ReadAsStringAsync() |> Async.AwaitTask |> Async.RunSynchronously
之后,我使用了JsonConvert.DeserializeObject:
JsonConvert.DeserializeObject<Response>(json)
附录:
if response.IsSuccessStatusCode
then let json = response.Content.ReadAsStringAsync() |> Async.AwaitTask |> Async.RunSynchronously
let result = JsonConvert.DeserializeObject<Response>(json);