Arne Lund
Arne Lund

Reputation: 2446

How to get the name of the token

I need to parse json files which look as follows:

{"20120101":{"Jeff":{"Status":"Sleepy", "Weight":212}, "Cathy":{"Status":"Angry", "Weight":172}}
{"20120102":{"Jeff":{"Status":"Alert", "Weight":207}, "Cathy":{"Status":"Sick", "Weight":168}}

I cannot figure out a way to extract the dates (20120101 and 20120102) and names (Jeff and Cathy) from my json. My attempts look as follows:

   private void LoadFile(string fileName)
    {
        var json = File.ReadAllText(fileName);
        JObject days = JObject.Parse(json);
        foreach (var dayAsObject in days)
        {
            var day = (JToken) dayAsObject;
            var a = day.Root.ToString();
            var t = day.ToString();
            var z = day.First;
            Console.WriteLine(day+t+z+a);
        }

Upvotes: 0

Views: 466

Answers (1)

FlavorScape
FlavorScape

Reputation: 14279

Better formulated json would look like

 {"20120101":{ "name":"Jeff", "Status":"Sleepy", "Weight":212}, { "name":"Cathy", "Status":"Angry", "Weight":172}}

Then it is very easy to get day["name"]. I would suggest modifying your json. If you absolutely cant, I think the property you're looking for is PropertyName.

I tend to use the built in System.Web.Script.Serialization JSON libary. If you don't need to do fancy stuff it works great with the dynamic object type.

Upvotes: 1

Related Questions