acidzombie24 acidzombie24 - 24 days ago 6
C# Question

How do I get all the fields using json.net?

A third party is giving me something similar to the below. When I know the key (such as

easyField
) getting the value is easy. Below I write it in the console. However the third party gave me json that uses random keys. How do I access it?

{
var r = new Random();
dynamic j = JsonConvert.DeserializeObject(string.Format(@"{{""{0}"":""hard"", ""easyField"":""yes""}}", r.Next()));
Console.WriteLine("{0}", j["easyField"]);
return;
}

Answer

You can use reflection with JSON.NET! It will give you the keys of your fields.

Try it online: Demo

using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;


public class Program
{
    public IEnumerable<string> GetPropertyKeysForDynamic(dynamic dynamicToGetPropertiesFor)
    {
        var attributesAsJObject = dynamicToGetPropertiesFor;
        var values = attributesAsJObject.ToObject<Dictionary<string, object>>();
        return values.Keys;
    }

    public void Main()
    {
        var r = new Random();
        dynamic j = JsonConvert.DeserializeObject(string.Format(@"{{""{0}"":""hard"", ""easyField"":""yes""}}", r.Next()));

        foreach(string property in GetPropertyKeysForDynamic(j))
        {
            Console.WriteLine(property);
            Console.WriteLine(j[property]);
        }
    }
}