我需要动态创建JToken
。必须通过某个对象的字符串字段构造Brand p["properties"]["brand"][0]
属性。我希望能够将其放在文本框中:["properties"]["dog"][0]
并让它成为品牌选择。
到目前为止,我的选择硬编码如下:
JObject o = JObject.Parse(j);
JArray a = (JArray)o["products"];
var products = a.Select(p => new Product
{
Brand = (string)p["properties"]["brand"][0]
}
但是我需要这样的东西:
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]
}
这有可能吗?
答案 0 :(得分:1)
查看SelectToken
方法。听起来这就是你要找的东西,虽然路径语法与你建议的有点不同。这是一个例子:
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; }
}
输出:
abc
xyz