Reputation: 465
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?
Upvotes: 0
Views: 3317
Reputation: 129677
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
Upvotes: 2