2016-06-23 2 views
3

文字列のランダムなビットを持つキーを持っているため、その値を抽出することが困難です。私がランダムなビットを前もって知らないときは、どうやってそれをやりますか?C#:正規表現を使用してオブジェクト内のキーの値を取得

は、与えられた:

sample = {\"total_ra4jhga987y3h_power\": 30} 

が直接

dynamic obj = JsonConvert.DeserializeObject(sample); 
obj[@"^total_(.*)_power$"] ---> should give me 30 

答えて

3

代わりにJSONにLINQを使用してのような何かをすることが可能です。 JObjectとして解析すると、すべてのプロパティを繰り返し処理し、正規表現に一致するものを見つけることができます。

Regex regex = new Regex(...); 
JObject json = JObject.Parse(text); 
foreach (var property in json.Properties()) 
{ 
    if (regex.IsMatch(property.Name)) 
    { 
     ... 
    } 
} 
+0

私はプロパティ()を実行する必要がありました。 GetPropertiesのisnteadとそれはNewtonsoft.Jsonを使用して働いた – user299709

+1

@ user299709:うん、はい、ドキュメントを誤解。一定。 –

0

あなたはあなたの特性を通過して、正規表現のために自分の名前をテストするためにLINQを利用することができます

public static class JsonExtensions 
{ 
    public static Dictionary<string, JToken> PropertiesByRegexp(this JObject token, Regex regex) 
    { 
     return token.Properties() 
      .Where(p => regex.IsMatch(p.Name)) 
      .ToDictionary(p => p.Name, p => p.Value); 
    } 
} 

あなたは今、次のように、この拡張メソッドを使用することができます。

JObject sample = JsonConvert.DeserializeObject("{\"total_ra4jhga987y3h_power\": 30, \"not_matching\": 31}") as JObject; 

var result = sample.PropertiesByRegexp(new Regex("^total_(.*)_power$")); 

foreach (var propertyPair in result) 
{ 
    Console.WriteLine($"{propertyPair.Key}: {propertyPair.Value}"); 
} 

出力:

total_ra4jhga987y3h_power: 30

2
var jsonDict = JsonConvert.DeserializeObject<Dictionary<string,long>>(sample); 
Regex rg = new Regex("total_.*_power"); 
var key = jsonDict.Keys.First(k=>rg.IsMatch(k)); 
Console.log(jsonDict[key]);