2017-03-14 218 views
0

我需要動態創建JToken。品牌p["properties"]["brand"][0]屬性必須通過某個對象的字符串字段構造。我希望能夠把它放在一個文本框中:["properties"]["dog"][0]並讓它成爲品牌選擇。動態生成JToken對象

我迄今選擇硬編碼是這樣的:

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] 
} 

這可能不知?

回答

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 

小提琴:https://dotnetfiddle.net/xZfPBQ

+0

謝謝!對於無效檢查,我需要我的用戶將他的輸入分解爲獨立的屬性,我猜:) – Developerdeveloperdeveloper

+0

@NETMoney實際上,'SelectToken'處理屬性路徑中的空值。例如,如果您指定了'descriptions.brand [0]'而'brand'爲空,則返回null;它不會拋出異常。 –