0

I'm trying to get the child of a JToken. I would drill down via name but it's kind of random(ish) numbers and I wondered if there is a way to just select the child?

My current code is:

 var jobs = new Collection<Job>();

 JObject jObject = JObject.Parse(json);
 JToken jCharacter = jObject["Character"];

 var jClassJobs = jCharacter["ClassJobs"].Children();

 foreach (JToken jClassJob in jClassJobs)
 {                
     Int16 cId = (Int16)jClassJob.Value<short>("ClassID");
     Int16 cLevel = (Int16)jClassJob.Value<Int16>("Level");

     jobs.Add(new Job
     {
         Id = cId,
         Level = cLevel
     });
 }

 return jobs;

The json I'm trying to get my Id and Level from looks like this but the 10_10 in this example would be 10_20 in a different one, and then even 10_30 later on. It's got a pattern but trying to do it neatly:

{"10_10": {
  "ClassID": 10,
  "ExpLevel": 26675,
  "ExpLevelMax": 324000,
  "ExpLevelTogo": 297325,
  "IsSpecialised": false,
  "JobID": 10,
  "Level": 40
}}

Any suggestions would be appreciated, I've been trying for hours.

Levjski
  • 1
  • 2
  • Look at the documentation for [`JObject`](https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JObject.htm). Take note that _JObject_ implements the `IDictionary` interface. Thus, you can query and process an _JObject_ instance basically like an ordinary dictionary with the keys being the json property names present in the respective json object and the values being, well, the json values associated with the respective json properties... –  May 31 '19 at 23:41
  • That's awesome! I'll have a look in the morning. Thanks for your reply. – Levjski Jun 01 '19 at 00:15
  • By the way, it might be that JObject implements some of the members/methods from IDictionary as [_explicit interface implementations_](https://stackoverflow.com/questions/143405/c-sharp-interfaces-implicit-implementation-versus-explicit-implementation). If that is true (which means that you can't directly call/access those members/methods from a JObject variable/reference), cast the _JObject_ reference explicitly to _IDictionary_ and bob's your uncle... –  Jun 01 '19 at 00:18
  • 1
    Thank again for the help @elgonzo! I looked at the route you suggested but just couldn't get my head around it. Instead, I created a model to match the response and used JsonConvert.DeserializeObject. I had some trouble with it, but once I changed the ClassJob model to a Dictionary I could then see it all. – Levjski Jun 01 '19 at 13:42

0 Answers0