How deserialize Json with multiples objects [duplicate]
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.
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, "]");
}
The structure of the json in rates
can be deserialized to a Dictionary<string, CustomClass>
. You can deserialize the json using the following classes:
public class RatesData
{
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<RatesData>(json);
Demo