【发布时间】:2018-04-02 18:54:17
【问题描述】:
我在反序列化一些 JSON 并尝试访问 root.items 后收到以下错误:
root.items.Count |> should equal 2
System.NullReferenceException: '对象引用未设置为 对象的实例。'
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()
【问题讨论】:
-
你能添加你的模型类的代码吗?否则无法查看 Json 是否与模型匹配。
-
我的猜测是 http 请求没有返回您期望的响应,或者 ReadAsAsync 无法按您的预期工作。我会尝试用其中包含 json 的 StringContent 对象替换 http 请求,以帮助缩小问题范围。
-
嗨。测试上面定义的响应记录类型是“模型”。 response.Content.ReadAsAsync
()
标签: asp.net-web-api asp.net-core f# json.net