简体   繁体   中英

Generate a JToken object dynamically

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM