0

I have a problem, under http://www.pathofexile.com/api/public-stash-tabs link there is a huge API that returns a JSON string. Many of fields in this JSON are optional, that means they only appear if there is value present.

So theoretical "Item1" can have "abyssJewel" property but "item2" doesnt have to have "abyssJewel" property

When i try to query this JSON with JSON.Linq like this

AbyssJewel = (bool)item["abyssJewel"];

in the case of Item1 everything is good and it returns proper value but in case of Item2 i get exception "InvalidOperationException, Cannot access child value on Newtonsoft.Json.Linq.JProperty"

I understand its because for Item2 no abyssJewel property in JSON exists so it throws exception.

My question is this, how can i handle it so that instead of throwing exception it would return a default or null value for this particular field?

I have tried playing with Activator but couldnt make anything working on my own. Any tips?

im instantiating it like this:

apiPages.Add(new Page
            {
                Next_Change_Id = (string)jsonObject["next_change_id"],
                Stashes = jsonObject["stashes"].Select(stash => new Stash
                {
                    AccountName = (string)stash["accountName"],
                    StashName = (string)stash["stash"],
                    StashType = (string)stash["stashType"],
                    Public = (bool)stash["public"],
                    LastCharacterName = (string)stash["lastCharacterName"],
                    UniqueId = (string)stash["id"],
                    Items = stash.Select(item => new Item
                                        {
                                            AbyssJewel = (bool)item["abyssJewel"],
...tl;dr...
XomRng
  • 171
  • 12
  • what type is `item`? – Daniel A. White Mar 13 '18 at 18:37
  • its JToken from JSON.NET – XomRng Mar 13 '18 at 18:37
  • You can use `SelectTokens()` or the null conditional operator as shown [here](https://stackoverflow.com/a/42300875/3744182). And when casting to a value type, cast to a nullable instead, e.g. `AbyssJewel = (bool ?)item["abyssJewel"].GetValueOrDefault();` – dbc Mar 13 '18 at 18:51
  • 2
    Or, just deserialize directly to a c# model without using the intermediate `JToken` representation at all. – dbc Mar 13 '18 at 18:52
  • My error was that i was trying deserialise the JSON directly to my Entity Framework model, which would require alot of tweaking and polluting the model with JSON annotations (unless there is some kind of Fluent API for JSON im not aware of?). The solution for my problem was in fact creation of a JSON model to which i could deserialise my JSON. Thanks dbc. – XomRng Mar 14 '18 at 09:54

1 Answers1

0

Instead of casting directly you should try to use the TryParse() method from the Boolean class, if something goes wrong it must return false. See here

Hope it will fix your problem.