2017-03-14 9 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

ありがとう! nullcheckingのために私はあなたの入力を別のプロパティに分解する必要があります: – Developerdeveloperdeveloper

+0

@NETMoney実際には、 'SelectToken'はプロパティパスに沿ってnull値を処理します。たとえば、 'description.brand [0]'と 'brand'を指定した場合、nullが返されます。例外をスローしません。 –

関連する問題