8

I have a json file which has random names in roots but same structure in child elements. I would like to get all the child elements in an array or a list.

Sample json file :

{  
   "-LeHl495vL6vh-8CaLbD":{  
      "apiKey":"sr-tr-137-beea04e44cb452ba0da0ca090b7e61b4ec6ffc69"
   },
   "-LeHl6jrhUEMb7slZcpB":{  
      "apiKey":"sr-tr-137-aef7a23095c0c7baef1ef681bdd8bf9756ac2a17"
   }
}

I have tried these classes but could not do it.

public class RequestedReport
    {
        public Dictionary<string, List<ReportData>> ReportDatas { get; set; }
    }

    public class ReportData
    {
        public string apiKey { get; set; }
    }

So my expected output from deserialization is like List which contains all the apiKeys in json file.

Thanks in advance.

3
  • Are there multiple apiKey entries in each object or just the one? Commented May 10, 2019 at 14:25
  • Just one api key in each node. Commented May 10, 2019 at 14:27
  • The Jon has your answer :) Commented May 10, 2019 at 14:27

1 Answer 1

11

It looks to me like your JSON represents a Dictionary<string, ReportData> directly. There's no wrapper object, and no lists involved. If you deserialize your JSON to that type, it should be fine. Here's a complete example:

using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;

class Program
{
    static void Main()
    {
        var json = File.ReadAllText("test.json");
        var reports = JsonConvert.DeserializeObject<Dictionary<string, ReportData>>(json);

        foreach (var pair in reports)
        {
            Console.WriteLine($"{pair.Key}: {pair.Value.ApiKey}");
        }
    }
}

public class ReportData
{
    [JsonProperty("apiKey")]
    public string ApiKey { get; set; }
}

If you just want the list of API keys, and you don't care about the field names associated with them, you can use:

var apiKeys = reports.Values.Select(x => x.ApiKey).ToList();
Sign up to request clarification or add additional context in comments.

4 Comments

Does this work if the random values are not guaranteed to be unique?
I think the deserialization into a dictionary would fail for duplicate keys, and I see nothing in your original question that promises uniqueness for this value. It certainly looks unique, but I've learned not to trust data.
@Broom Yes, this wouldn't work for non-unique values. I believe JSON.Net would take the last apiKey for each key.
@Broom: From RFC 7159: "When the names within an object are not unique, the behavior of software that receives such an object is unpredictable." In other words, anything producing such JSON is really just asking for trouble.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.