user34537
user34537

Reputation:

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;
}

Upvotes: 1

Views: 2451

Answers (2)

aloisdg
aloisdg

Reputation: 23521

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 jObject)
    {
        return jObject.ToObject<Dictionary<string, object>>().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]);
        }
    }
}

Edit:

An even simpler solution:

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

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

        foreach(var property in j.ToObject<Dictionary<string, object>>())
        {
            Console.WriteLine(property.Key + " " + property.Value);
        }
    }
}

Upvotes: 2

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34160

This is what I had used in my project to get fields and values of a class:

public static List<KeyValuePair> ClassToList(this object o)
{
    Type type = o.GetType();
    List<KeyValuePair> vals = new List<KeyValuePair>();
    foreach (PropertyInfo property in type.GetProperties())
    {
        if (!property.PropertyType.Namespace.StartsWith("System.Collections.Generic"))
        {
              vals.Add(new KeyValuePair(property.Name,(property.GetValue(o, null) == null ? "" : property.GetValue(o, null).ToString()))
        }
    }
    return sb.ToString();
}

Note that the reason I was checking !property.PropertyType.Namespace.StartsWith("System.Collections.Generic") as It was causing infinte loops in entity models and if that is not the case you can remove the if condition.

Upvotes: 0

Related Questions