[英]Generate a JToken object dynamically
I need to create a JToken
dynamically. 我需要动态创建一个
JToken
。 The Brand p["properties"]["brand"][0]
property must be constructed via string fields from some object. 必须通过某些对象的字符串字段构造Brand
p["properties"]["brand"][0]
属性。 I want to be able to put this in a textbox: ["properties"]["dog"][0]
and let that be the brand selection. 我希望能够将其放在文本框中:
["properties"]["dog"][0]
然后将其作为品牌选择。
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. 看看
SelectToken
方法。 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 小提琴: https : //dotnetfiddle.net/xZfPBQ
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.