0
 var ans = await client.GetStringAsync(uri);
        JToken[] JSONResponseWeb = new JToken[1];
        JToken[] JSONResponseImage = new JToken[1];

        JSONResponseWeb = JToken.Parse(ans)["webPages"]["value"].ToArray();

        JSONResponseImage = JToken.Parse(ans)["images"]["value"].ToArray();

How to prevent null reference function here? ie...suppose the api that i consume doesnt have a property "images"

Gp_1993
  • 89
  • 11
  • what is the shortest possible way...something like isnull etc? – Gp_1993 Apr 19 '17 at 13:16
  • Depends what you want to happen if it's null. – schroedingersKat Apr 19 '17 at 13:17
  • 1
    Why are you manually parsing? Is there any reason why you can not create a class with required properties and use JsonConvert.DeserializeObject?? If you want to prevent NullReferenceException, you can use TryParse. – sam Apr 19 '17 at 13:17
  • Thats the kind of answer am looking for @sam but TryParse is not available??? I guess... – Gp_1993 Apr 19 '17 at 13:20
  • 1
    @Gp_1993 this isn't an issue of parsing. You are parsing correctly or you'd get an exception on the first parse (webPages) this is an issue of you trying to access a value that doesn't exist. It returns null and then you try to access the value on it. – thinklarge Apr 19 '17 at 13:22

2 Answers2

0

Shortest way (C# 6 and higher):

JSONResponseImage = JToken.Parse(ans)?["images"]?["value"]?.ToArray();

Other ways (also below C# 6):

JSONResponseImage = null;
var parseResult = JToken.Parse(ans);
if (parseResult != null)
    if (parseResult["images"] != null)
        if (parseResult["images"]["value"] != null)
            JSONResponseImage = parseResult["images"]["value"].ToArray();

Or (not good style, avoid it):

var parseResult = JToken.Parse(ans);
JSONResponseImage = parseResult != null
                    ? (parseResult["images"] != null
                       ? (parseResult["images"]["value"] != null
                          ? parseResult["images"]["value"].ToArray()
                          : null)
                       : null)
                    : null;

Worst way (see comments):

JSONResponseImage = null;
try
{
    JSONResponseImage = JToken.Parse(ans)["images"]["value"].ToArray();
}
Benjamin Krupp
  • 933
  • 7
  • 16
  • Catching an exception in the first example is a pretty bad practice in C#. It's an expensive operation you should try to avoid doing first. Try the second or third option as a preference. – thinklarge Apr 19 '17 at 13:20
  • You also shouldn't be performing an expensive parsing operation multiple times. – Servy Apr 19 '17 at 13:22
  • I'll edit. Didn't realize that an expensive parsing operation is going on with that code, but it's obvious. – Benjamin Krupp Apr 19 '17 at 13:23
  • @BenjaminKrupp You have to check each access to an index to see if it returns a null. Your top answer will still return null if ["images"] returns null. Then you get a null reference exception when you try to get the value of that null. You have to put the ? operator at each point that you might be trying to access anything on a null value. So do something like this JSONResponseImage = JToken.Parse(ans)?["images"]?["value"]?.ToArray(); Even then in the OPs post he was parsing two times so this optimization can be further broken down but that comes down to style. – thinklarge Apr 19 '17 at 13:35
  • 1
    @thinklarge I misread the question (skipped over 'ie...suppose'). That's why I was only going on about `["images"]` all the time! ;) I made the answer more general. – Benjamin Krupp Apr 20 '17 at 08:54
0
var ans = await client.GetStringAsync(uri);
    JToken[] JSONResponseWeb = new JToken[1];
    JToken[] JSONResponseImage = new JToken[1];
    var responseResult = JToken.Parse(ans);
    // Check if you have a null value anywhere in these parameters. This doesn't assume any handling for null values you'll have to figure that out on your end.  Add en else statement and go to town. 
    if (responseResult?["webPages"]?["value"] != null)
    {
        JSONResponseWeb = responseResult ["webPages"]["value"].ToArray();
    }

    if (responseResult?["images"]?["value"] != null)
    {
        JSONResponseWeb = responseResult ["images"]["value"].ToArray();
    }
thinklarge
  • 652
  • 8
  • 23
  • 1
    Why not check for null using elvis operator like this? `if (responseResult?["webPages"]?["value"] != null)` – schroedingersKat Apr 19 '17 at 13:22
  • @schroedingersKat Honestly I didn't know that worked ;-) But that is way better! First I have to verify that works because all I've ever seen is the ?. operator in action. Thanks for the trick! – thinklarge Apr 19 '17 at 13:27