CSharp · Console
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using NUnit.Framework; // Throws NUnit.Framework.AssertionException
//https://stackoverflow.com/questions/77856068/c-sharp-how-can-i-check-if-a-field-exists-before-trying-to-query-it-in-a-json
class TestClass
{
public static void Test()
{
Test0();
Console.WriteLine();
Test1();
Test2();
}
public static void Test0()
{
foreach (var jsonString in GetJson())
{
var result = JsonConvert.DeserializeObject<JToken>(jsonString);
var total = (string)result.SelectTokens("results.main[*].item.total").SingleOrDefault() ?? string.Empty;
if (!string.IsNullOrEmpty(total))
{
// Process the total somehow.
}
Console.WriteLine(total);
}
}
public static void Test1()
{
foreach (var jsonString in GetJson())
{
var result = JToken.Parse(jsonString);
var total = (string)result.SelectToken("results.main[0].item.total") ?? string.Empty;
if (!string.IsNullOrEmpty(total))
{
Console.WriteLine(total);
}
else
{
Console.WriteLine("no total");
}
}
}
public static void Test2()
{
foreach (var jsonString in GetJson())
{
var result = JToken.Parse(jsonString);
var items = result.SelectTokens("results.main[?(@.item.total)].item");
foreach (var item in items)
{
var name = (string)item["name"];
var total = (decimal)item["total"];
Console.WriteLine("name = {0}, total = {1}", name, total);
}
}
}
static IEnumerable<string> GetJson()
{
return new []
{
@"{
""results"": {
""copyright"": ""Copyright (c)"",
""main"": [{
""item"": {
""name"": ""fruit"",
""date"": ""1900-01-01"",
""total"": 123456
}
}]
}
}
",
@"{
""results"": {
""copyright"": ""Copyright (c)"",
""main"": [{
""item"": {
""name"": ""flubber"",
""date"": ""1900-01-01"",
}
}]
}
}",
};
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Environment version: " + Environment.Version);
Console.WriteLine("{0} version: {1}", typeof(JsonSerializer).Namespace, typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine();
try
{
TestClass.Test();
}
catch (Exception ex)
{
Console.WriteLine("Failed with unhandled exception: ");
Console.WriteLine(ex);
throw;
}
}
}