Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How deserialize Json with multiples objects

I’ve received a JSON from a Web API to build an MVC application. (https://api.coingecko.com/api/v3/exchange_rates)

The structure look’s like this:

{
  "rates": {
    "btc": {
      "name":"Bitcoin",
      "unit":"BTC",
      "value":1.0,
      "type":"crypto"
    },
    "eth":{
      "name":"Ether",
      "unit":"ETH",
      "value":12.954,
      "type":"crypto"
    },...

When I use "Paste JSON as Classes" it’s generate a huge list of classes and a Root Object with a lot of properties.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’m deserializing it like this:

Rootobject myDeserializedClass = JsonConvert.DeserializeObject<Rootobject>(jsonstring)

There’s a better way of doing that?

Edit:

I was using a different class for each of the objects:

Exemple:

public class Btc
    {
        public string name { get; set; }
        public string unit { get; set; }
        public double value { get; set; }
        public string type { get; set; }
    }

    public class Eth
    {
        public string name { get; set; }
        public string unit { get; set; }
        public double value { get; set; }
        public string type { get; set; }
    }

    public class Ltc
    {
        public string name { get; set; }
        public string unit { get; set; }
        public double value { get; set; }
        public string type { get; set; }
    }

I’m beginner C# student and didn’t thought about using Dictionary.
A had a code with 66 different classes and a method as below:

var requisicaoWeb = WebRequest.CreateHttp("https://api.coingecko.com/api/v3/exchange_rates");
requisicaoWeb.Method = "Get";
requisicaoWeb.UserAgent = "RequisicaoWebDemo";

using (var resposta = requisicaoWeb.GetResponse())
{
    var streamDados = resposta.GetResponseStream();
    StreamReader reader = new StreamReader(streamDados);
    object objResponse = reader.ReadToEnd();
    var jsonstring = objResponse.ToString().Replace("{\"rates\":", "");
    jsonstring = jsonstring.Remove(jsonstring.Length - 1);
    streamDados.Close();
    resposta.Close();
    Rootobject myDeserializedClass = JsonConvert.DeserializeObject<Rootobject>(jsonstring);
    
    foreach (var p in myDeserializedClass.GetType().GetProperties().Where(p => !p.GetGetMethod().GetParameters().Any()))
    {      
        var test = (p.GetValue(myDeserializedClass));
        if(test!=null)
        {
         string lol = test.ToString().ToLower();
            jsonstring = jsonstring.Replace($"\"{lol}\":", "");
        }         
    }

    jsonstring = jsonstring.Remove(jsonstring.Length - 1)
                           .Remove(0,1)
                           .Replace($"\"try\":", "")
                           .Insert(0, "[");
    jsonstring = jsonstring.Insert(jsonstring.Length, "]");   
}

>Solution :

The rates json can be modelled as a Dictionary<string, CustomClass>. Using the following classes you should be able to deserialize the json:

public class MyData
{
    public Dictionary<string, CryptoData> Rates { get;set;}
}

public class CryptoData
{
    public string Name { get;set;}
    public string Unit { get;set;}
    public string Value { get;set;}
    public string Type { get;set;}
}

And deserialize (using Newtonsoft.Json):

var model = JsonConvert.DeserializeObject<MyData>(json);

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading