fsprojects / FSharp.Json

F# JSON Reflection based serialization library
Apache License 2.0
226 stars 26 forks source link

Unhandled Exception when deserializing a list of objects #10

Closed nobleach closed 6 years ago

nobleach commented 6 years ago

I have a bit of JSON that looks like this:

[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
  }
]

I'm attempting to deserialize it like this:

type User =
  { userId: int
    id: int
    title: string
    body: string }

// code that fetches a string of json

let deserialized = Json.deserialize<User list> json

I'm getting Unhandled Exception: FSharp.Json.JsonDeserializationError: JSON Path: [100].userId. Non option field is missing.

I'm not sure what this means. I'd guess that the JSON is somehow missing that field. What is the correct step to take if I might expect that to be the case (I don't currently, but what if?)

vsapronov commented 6 years ago

If looks like in one of the objects (the one with #100) in your list there is no field 'userId'. If field could be missing then it should be of option type, userId: int option in your case.

nobleach commented 6 years ago

Yes, that solve this issue perfectly. Thank you so much!

vsapronov commented 6 years ago

This page mentions missing fields https://vsapronov.github.io/FSharp.Json/null_safety.html And here are some details about controlling null VS missing fields behaviour: https://vsapronov.github.io/FSharp.Json/null_safety.html#Customization-of-null-deserialization

nobleach commented 6 years ago

Great! Thanks again.