0

I need to create a JToken dynamically. The Brand p["properties"]["brand"][0] property must be constructed via string fields from some object. I want to be able to put this in a textbox: ["properties"]["dog"][0] and let that be the brand selection.

Thus far I have the selection hardcoded like this:

JObject o = JObject.Parse(j);
JArray a = (JArray)o["products"];

var products = a.Select(p => new Product
{
    Brand = (string)p["properties"]["brand"][0]
}

I however need something like this:

JObject o = JObject.Parse(j);
JArray a = (JArray)o["products"];
string BrandString = "['descriptions']['brand'][0]";

var products = a.Select(p => new Product
{
    Brand = (string)p[BrandString]
}

Is this possible somehow?

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
Viking
  • 465
  • 3
  • 15

1 Answers1

2

Have a look at the SelectToken method. It sounds like that is what you are looking for, although the path syntax is a bit different than what you have suggested. Here is an example:

public class Program
{
    public static void Main(string[] args)
    {
        string j = @"
        {
          ""products"": [
            {
              ""descriptions"": {
                ""brand"": [ ""abc"" ]
              }
            },
            {
              ""descriptions"": {
                ""brand"": [ ""xyz"" ]
              }
            }
          ]
        }";

        JObject o = JObject.Parse(j);
        JArray a = (JArray)o["products"];
        string brandString = "descriptions.brand[0]";

        var products = a.Select(p => new Product
        {
            Brand = (string)p.SelectToken(brandString)
        });

        foreach (Product p in products)
        {
            Console.WriteLine(p.Brand);
        }
    }
}

class Product
{
    public string Brand { get; set; }
}

Output:

abc
xyz

Fiddle: https://dotnetfiddle.net/xZfPBQ

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
  • Thanks! For nullchecking i would need my user to decompose his input to separate properties i guess :) – Viking Mar 16 '17 at 06:36
  • @NETMoney Actually, `SelectToken` handles null values along the property path. For example, if you specified `descriptions.brand[0]` and `brand` was null, then the null would be returned; it would not throw an exception. – Brian Rogers Mar 16 '17 at 13:35
  • You might be able to answer this one as well? https://stackoverflow.com/questions/64313721/adding-a-complex-object-to-jobject-using-a-delimited-key?noredirect=1#comment113726010_64313721 – CodeMonkey Oct 12 '20 at 08:07