Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize json with c# with random root names

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.

like image 291
Ebubekir Çağrı Şen Avatar asked May 10 '19 14:05

Ebubekir Çağrı Şen


People also ask

How do I deserialize JSON data?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

How JSON deserialization works in C#?

In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom . Net object. In the following code, it calls the static method DeserializeObject() of the JsonConvert class by passing JSON data. It returns a custom object (BlogSites) from JSON data.

Does C have JSON?

JSON-C implements a reference counting object model that allows you to easily construct JSON objects in C, output them as JSON formatted strings and parse JSON formatted strings back into the C representation of JSON objects. It aims to conform to RFC 7159.


1 Answers

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();
like image 52
Jon Skeet Avatar answered Oct 04 '22 17:10

Jon Skeet