在反序列化某些JSON并尝试访问root.items后,我收到以下错误:
ServiceProvider
System.NullReferenceException:'对象引用未设置为 一个对象的实例。'
root.items @为null。
JSON如下:
root.items.Count |> should equal 2
这是我的代码:
{
"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",
]
}
}
]
}
答案 0 :(得分:1)
我刚刚为它编写了一个测试,我可以确认它的反序列化部分是正确的。检查请求是否正确返回响应。
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"
}
]
答案 1 :(得分:0)
following为我工作:
总之,我不得不求助于使用以下方法检索实际的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);