2016-05-06 18 views
0

C#でJSON.NETを使用して複雑なJSONオブジェクト内で見つかった列挙型(プロパティが存在するかどうかを調べる) ?C#でJSON.Netを使用して複雑なJSONオブジェクトをクエリおよび列挙する方法

APIから複雑な番号/タイプのプロパティを使用して複合JSONオブジェクトを受信して​​います。

私はそれが含まれていることを確認し、私はpageResponses.scriptOutputプロパティを見つけたい

...など、ダイナミック使って、JToken、サンプルなどではなく、これまで得とjオブジェクト、JArrayで失われていますを見直し、the JSON.Net Documentationを読み続けます.items[]配列を作成し、配列を列挙/反復します。

編集

私は進歩を遂げたとJSONデータの例では、タイプミスを発見しました。

しかし、(item.location, item.timestamp)などのキー名を使用して子オブジェクトをクエリ/列挙するにはどうすればよいですか?

string json = File.ReadAllText(@"Output.json"); 
JObject jObj = JObject.Parse(json); 

IList<JToken> items = jObj["pageResponses"][0]["scriptOutput"]["items"].ToList(); 
foreach (JToken item in items){ 
    Console.WriteLine(item["location"]); 
} 
/*** Console Output ***/ 
// Austin, TX 
// Anaheim, CA 
// Adams, MN 
// Barstow, CA 

var varItems = from o in jObj["pageResponses"][0]["scriptOutput"]["items"].ToList() select o; 

foreach (var item in varItems){ 
    Console.WriteLine(item["timestamp"]); 
} 
/*** Console Output ***/ 
// 2016 - 05 - 03 19:53 
// 2016 - 05 - 04 04:10 
// 2016 - 05 - 04 08:18 
// 2016 - 05 - 01 12:26 

(以下JSONのサンプルを簡潔にするためにトリムダウン)

{ 
    "meta": { 
    "outputAsJson": true, 
    "backend": { 
     "os": "linux", 
     "id": "10.240.0.3_2", 
     "requestsProcessed": 8 
    } 
    }, 
    "pageResponses": [ 
    { 
     "pageRequest": { 
     "renderType": "script", 
     "outputAsJson": true 
     }, 
     "frameData": { 
     "name": "", 
     "childCount": 1 
     }, 
     "events": [ 
        { 
        "key": "navigationRequested", 
        "time": "2016-05-06T13:43:30.344Z" 
        }, 
        { 
        "key": "navigationRequested", 
        "time": "2016-05-06T13:43:31.131Z" 
        } 
     ], 
     "scriptOutput": { 
     "items": [ 
      { 
      "location": "Austin, TX", 
      "timestamp": "2016-05-03 19:53", 
      "title": "User Login" 
      }, 
      { 
      "location": "Anaheim, CA", 
      "timestamp": "2016-05-04 04:10", 
      "title": "User Logout" 
      }, 
      { 
      "location": "Adams, MN", 
      "timestamp": "2016-05-04 08:18", 
      "title": "User Login" 
      }, 
      { 
      "location": "Barstow, CA", 
      "timestamp": "2016-05-01 12:26", 
      "title": "User Logout" 
      } 
     ] 
     }, 
     "statusCode": 200 
    } 
    ], 
    "statusCode": 200, 
    "content": { 
    "name": "content.json", 
    "encoding": "utf8" 
    }, 
    "originalRequest": { 
    "pages": [ 
     { 
     "renderType": "script", 
     "outputAsJson": true 
     } 
    ] 
    } 
} 
+0

クラス階層を作成できます。デシリアライズしたくないプロパティの場合は、「動的」を使用できます。階層を通過する場合は、再帰関数を使用する必要があります。 –

+0

もう1つの重要な点は、JSONを検証する場合、作成するスキームに対してJSON.Netバリデーターを使用できることです。 Look [here](http://www.jsonschemavalidator.net/) –

+0

この[documentation](http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Schema_JsonSchema.htm)の 'parse'メソッドを見てください。 –

答えて

2

私は(私はjson2csharpを使用)プロキシクラスを作成するお勧め:

public class Backend 
{ 
    public string os { get; set; } 
    public string id { get; set; } 
    public int requestsProcessed { get; set; } 
} 

public class Meta 
{ 
    public bool outputAsJson { get; set; } 
    public Backend backend { get; set; } 
} 

public class PageRequest 
{ 
    public string renderType { get; set; } 
    public bool outputAsJson { get; set; } 
} 

public class FrameData 
{ 
    public string name { get; set; } 
    public int childCount { get; set; } 
} 

public class Event 
{ 
    public string key { get; set; } 
    public string time { get; set; } 
} 

public class ScriptOutput 
{ 
    public List<object> items { get; set; } 
} 

public class PageRespons 
{ 
    public PageRequest pageRequest { get; set; } 
    public FrameData frameData { get; set; } 
    public List<Event> events { get; set; } 
    public ScriptOutput scriptOutput { get; set; } 
    public int statusCode { get; set; } 
} 

public class Content 
{ 
    public string name { get; set; } 
    public string encoding { get; set; } 
} 

public class Page 
{ 
    public string renderType { get; set; } 
    public bool outputAsJson { get; set; } 
} 

public class OriginalRequest 
{ 
    public List<Page> pages { get; set; } 
} 

public class RootObject 
{ 
    public Meta meta { get; set; } 
    public List<PageRespons> pageResponses { get; set; } 
    public int statusCode { get; set; } 
    public Content content { get; set; } 
    public OriginalRequest originalRequest { get; set; } 
} 

そして、それをデシリアライズ:

var obj = JsonConvert.DeserializeObject<RootObject>(json); 
if (obj != null && obj.pageResponses != null) 
{ 
    foreach (var pageResponse in obj.pageResponses) 
    { 
     if (pageResponse.scriptOutput == null) 
      continue; 

     foreach (var item in pageResponse.scriptOutput.items) 
     { 
      Console.WriteLine(item); 
     } 
    } 
} 
+0

これは実際に配列をチェックして列挙する方法を少し助けますか? – Newport99

+0

私は答えを更新しました。今はっきりしていますか?デバッガを使用してオブジェクトの構造を調べることで、それを処理するコードを記述するのに役立ちます。 –

+0

RootObjectの名前空間とは何ですか? JSON.NETや.NETのオンラインドキュメントのどこにも見つかりません。 – Newport99

0

Iいくつかの拡張メソッドでこれを行い、JsonConvert.DeserializeObjectを使用します。

下記のコードスニペット。私はプロパティが存在チェック上記のコードでは

使用

ExpandoObject data = JsonConvert.DeserializeObject<ExpandoObject>(jsonString); 
if(data.HasProperty("propertyToCheck")) 
{ 
    object[] objects = data.Get<object[]>("propertyToCheck"); 
} 

、私はこの場合、オブジェクトの配列で、.NET型に割り当てます。それは正気であればどんなタイプでも構いません。

拡張メソッド

public static bool HasProperty(this ExpandoObject value, string property) 
{ 
    bool hasProp = false; 
    if (((IDictionary<String, object>)value).ContainsKey(property)) 
    { 
     hasProp = true; 
    } 
    return hasProp; 
} 

public static T Get<T>(this ExpandoObject value, string property) 
{ 
    return (T)((IDictionary<String, dynamic>)value)[property]; 
} 

、簡単迅速かつポイントに!

関連する問題