2015-07-12 7 views
5

mam tekst json tak:C# Metoda JToken.SelectTokens - jakie wyrażenie JPath?

{ 
"course_editions": { 
"2014/SL": [ 
    { 
    "grades": { 
     "course_units_grades": { 
     "159715": { 
      "1": { 
      "value_symbol": "4", 
      "exam_session_number": 1, 
      "exam_id": 198172, 
      "value_description": { 
       "en": "good", 
      } 
      } 
     } 
     }, 
     "course_grades": {} 
    } 
    }, 
    { 
    "grades": { 
     "course_units_grades": { 
     "159796": { 
      "1": { 
      "value_symbol": "5", 
      "exam_session_number": 1, 
      "exam_id": 198259, 
      "value_description": { 
       "en": "very good", 
      } 
      } 
     } 
     }, 
     "course_grades": {} 
    } 
    }, 

Chciałbym użyć metody JToken.SelectTokens z przestrzeni nazw: Newtonsoft.Json.Linq

Próbowałem tak:

string json_response = GetResponse(sign(url_courses)); 
var courses_tokens = JObject.Parse(json_response).SelectTokens("['course_editions'].['2014/SL'].[*].['grades'].*") 

To nie działa. Chciałbym uzyskać tylko te numery po course_unit_grades i przed "1". Tak więc w tym przykładzie tylko: "159715" i "159796", aby móc korzystać z wszystkich z nich, jeden po drugim w

foreach(var lp in courses_tokens) { 
} 

Odpowiedz

2

Jest to jeden z możliwych sposobów:

var jobj = JObject.Parse(json); 
var coursesTokens = jobj.SelectTokens("course_editions.2014/SL[*].grades.course_units_grades") 
         .Select(o => o.First) //get the first child of `course_units_grades` 
         .Cast<JProperty>() //cast to JProperty 
         .Select(o => o.Name); //get the name of the property 
foreach (string coursesToken in coursesTokens) 
{ 
    Console.WriteLine(coursesToken); 
} 

Dotnetfiddle Demo

podana próba json na dole, wyjście jest następujące:

159715 
159796 

json próbki:

var json = @"{ 
    'course_editions': { 
     '2014/SL': [ 
     { 
      'grades': { 
       'course_units_grades': { 
        '159715': { 
        '1': { 
         'value_symbol': '4', 
         'exam_session_number': 1, 
         'exam_id': 198172, 
         'value_description': { 
          'en': 'good' 
         } 
        } 
        } 
       }, 
       'course_grades': {} 
      } 
     }, 
     { 
      'grades': { 
       'course_units_grades': { 
        '159796': { 
        '1': { 
         'value_symbol': '5', 
         'exam_session_number': 1, 
         'exam_id': 198259, 
         'value_description': { 
          'en': 'very good' 
         } 
        } 
        } 
       }, 
       'course_grades': {} 
      } 
     } 
     ] 
    } 
}"; 
+0

Mój przykład nie przewiduje takiej sytuacji, ale nie może być więcej niż jedno dziecko w 'course_units_grades', max. 3, ale w tym konkretnym przypadku mam problem z '.Select (o => o.First)', Czy jest jakiś inny sposób? –

Powiązane problemy