Deserialize JSON data in to a class in c# - json

hello people I have this Json data:
https://openexchangerates.org/api/latest.json?app_id=6cf59607a32d408eb3e04de1427a3169
and I want to deserialize in the following class
using Newtonsoft.Json;
using System.Collections.Generic;
namespace Divisas2MVVM2.Classes
{
public class ExchangeRates
{
[JsonProperty(PropertyName = "disclaimer")]
public string Disclaimer { get; set; }
[JsonProperty(PropertyName = "license")]
public string License { get; set; }
[JsonProperty(PropertyName = "timestamp")]
public int TimeStamp { get; set; }
[JsonProperty(PropertyName = "base")]
public string Base { get; set; }
[JsonProperty(PropertyName = "rates")]
public Rates Rates { get; set; }
}
public class Rates
{
public double AED { get; set; }
public double AFN { get; set; }
public double ALL { get; set; }
public double AMD { get; set; }
// I cut the text so that it would not be to long
public double ZMW { get; set; }
public double ZWL { get; set; }
}
public class Rate
{
public double TaxRate { get; set; }
public string Code { get; set; }
}
this is my attribute
private ExchangeRates exchangeRates;
the constructor of my MainViewModel
new ObservableCollection data
Rates = new ObservableCollection<Rate>();
and in this method a get the json data
try
{
var client = new HttpClient();
client.BaseAddress = new Uri("https://openexchangerates.org");
var url = "/api/latest.json?app_id=6cf59607a32d408eb3e04de1427a3169";
var response = await client.GetAsync(url);
if (!response.IsSuccessStatusCode)
{
Message = response.StatusCode.ToString();
IsRunning = false;
return;
}
var result = await response.Content.ReadAsStringAsync();
exchangeRates = JsonConvert.DeserializeObject<ExchangeRates>(result);
}
everything works fine, the variable result has correctly the json data in a string format, but when i call JsonConvert . DeserializeObject, the data "rates" it is not assigned correctly, all the other data: disclaimer", "license", "timestamp" etc. is correctly assigned. only rates fail.
the string is correct
other data is correct in the class
rates is incorrect
sorry for my English I hope you have understood me :)

use this as your model class
namespace Rate
{
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public partial class Rates
{
[JsonProperty("disclaimer")]
public string Disclaimer { get; set; }
[JsonProperty("license")]
public string License { get; set; }
[JsonProperty("timestamp")]
public long Timestamp { get; set; }
[JsonProperty("base")]
public string Base { get; set; }
[JsonProperty("rates")]
public Dictionary<string, double> RatesRates { get; set; }
}
public partial class Rates
{
public static Rates FromJson(string json) => JsonConvert.DeserializeObject<Rates>(json, Rate.Converter.Settings);
}
public static class Serialize
{
public static string ToJson(this Rates self) => JsonConvert.SerializeObject(self, Rate.Converter.Settings);
}
internal static class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
Converters = {
new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
},
};
}
}
Then do this in your class
var data = Rate.Rates.FromJson("jsonresult");
var rate = data.RatesRates;
foreach (var pair in rate)
{
string symbol = pair.Key; //"AED"
double value = pair.Value; //3.673175,
}
var time = data.Timestamp;
var disclaimer = data.Disclaimer;
var license = data.License;
Tested and working

Related

How can I implement JSON file into a drop down list for countries in a validation form?

I tried with this code, but it doesn't seem to work.
public ActionResult Getcountries()
{
var webClient = new WebClient();
var json = webClient.DownloadString(#"C:\Users\kristijanm\source\repos\contactForm\contactForm\data\Countries.json");
var CountryL = JsonConvert.DeserializeObject<CountriesModel>(json);
return View(CountryL);
}
Here is my Model:
public class CountriesModel
{
public int Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
}
}

Can't get API input list and convert it to json and get its contents

I have an API that as an input I have:
myMedicineJsonList=[{"medicineType":"ketamine","medicineDose":"5 drops","medicineDiode":"IV"},{"medicineType":"adrenaline","medicineDose":"5 drops","medicineDiode":"IV"}]
I need to get its contents and save it in a table in a database.
Currently I'm using the following code:
public partial class medicines
{
public int medicine{ get; set; }
public String medicineType { get; set; }
public String medicineDosage { get; set; }
public String medicinePlace { get; set; }
}
public System.Web.Http.Results.JsonResult<String> Insert_call_info( List<String> medicineList)
{
using (EMSMVCEntities entities = new EMSMVCEntities())
{
entities.Configuration.ProxyCreationEnabled = false;
try
{
var myMedicineJson = JsonConvert.SerializeObject(medicineList);
var myMedicineJsonList = JsonConvert.DeserializeObject<medicines>(myMedicineJson);
var medications = myMedicineJsonList.Value<JObject>("Medicine").ToObject<List<medicines>>();
var medicationsdb = entities.Set<Call_info_Medicines>();
...
}
}
}
However in myMedicineJsonList or in medications I can't get the contents of medicineList to store them in a table.
The table I want to store it is the following:
public partial class Call_info_Medicines
{
public int medicine_info_id { get; set; }
public string medicine { get; set; }
public string medicineType { get; set; }
public string medicineDosage { get; set; }
public string medicinePlace { get; set; }
}
I need to store it using the following line is the previous code snipset.
var medicationsdb = entities.Set<Call_info_Medicines>();
I found the following solution:
public class RootObject
{
public List<medicines> Medicine { get; set; }
}
var medResult = JsonConvert.DeserializeObject<RootObject>(medicineList);
var medicineTypeL = medResult.Medicine.Select(p => p.medicineType).ToList();
var medicineDosageL = medResult.Medicine.Select(p => p.medicineDosage).ToList();
var medicinePlaceL = medResult.Medicine.Select(p => p.medicinePlace).ToList();

deserialize json array of object c# RIOT API [NOT WORKING]

i've recently started to start on a new small project, but have come across some issues.. I'm not really sure why it's not working honestly.
public partial class MatchlistDto
{
public List<MatchHistory> matchhistory { get; set; }
}
public partial class MatchHistory
{
[JsonProperty("platformId")]
public string platformId { get; set; }
[JsonProperty("gameId")]
public long gameId { get; set; }
[JsonProperty("champion")]
public int champion { get; set; }
[JsonProperty("queue")]
public int queue { get; set; }
[JsonProperty("season")]
public int season { get; set; }
[JsonProperty("timestamp")]
public long timestamp { get; set; }
[JsonProperty("role")]
public string role { get; set; }
[JsonProperty("lane")]
public string lane { get; set; }
}
public partial class SummonerV4
{
public string id { get; set; }
public string accountId { get; set; }
public string puuid { get; set; }
public string profileIconId { get; set; }
public string revisionDate { get; set; }
public string summonerLevel { get; set; }
}
Code from Controller.
[HttpPost]
public async Task<ActionResult> DisplayAccount(string Region, string User)
{
string ApiKey = "TottalyAnApiKey";
SummonerV4 UserInfo = new SummonerV4();
using (var client = new HttpClient())
{
HttpResponseMessage Res = await client.GetAsync("https://" + Region + ".api.riotgames.com/lol/summoner/v4/summoners/by-name/"+ User +"?api_key="+ ApiKey);
if (Res.IsSuccessStatusCode)
{
var apiResponse = Res.Content.ReadAsStringAsync().Result; //First part is to get AccountInformation from user. e.g AccountID.
UserInfo = JsonConvert.DeserializeObject<SummonerV4>(apiResponse);
HttpResponseMessage Res2 = await client.GetAsync("https://" + Region + ".api.riotgames.com" + "/lol/match/v4/matchlists/by-account/" + User + "?api_key=" + ApiKey); //Second part is to collect the Match History from user.
if (Res2.IsSuccessStatusCode)
{
var PersonalResponse2 = Res2.Content.ReadAsStringAsync().Result;
List<MatchlistDto> matchHistoryList = JsonConvert.DeserializeObject<List<MatchlistDto>>(PersonalResponse2);
}
}
}
return View(UserInfo);
}
So whats going on is that, i do get the correct response from RiotGames API but i can't really deserialize it correctly. Please check images. My wish is to store the data in a list or array.
Here you can see all the objects from the response
And here the error
A couple problems:
1: MatchlistDto matchhistory field is misnamed
It should look like this:
public partial class MatchlistDto
{
public List<MatchHistory> matches { get; set; }
}
Or like this:
public partial class MatchlistDto
{
[JsonProperty("matches")]
public List<MatchHistory> matchhistory { get; set; }
}
2: API returns a MatchlistDto, not a List
Should write this:
MatchlistDto matchHistoryList = JsonConvert.DeserializeObject<MatchlistDto>(PersonalResponse2);

json parse from combobox data

want to parse a JSON string in combobox to 'text'. The response is something like
How can I parse the JSON and extract its 'text' values?
var restClient = new RestClient("https://cbsservis.tkgm.gov.tr/megsiswebapi.v2/api/idariYapi/ilListe");
var restRequest = new RestRequest(Method.GET);
var restResponse = restClient.Execute(restRequest);
restRequest.AddHeader("Accept", "text/json");
var jArray = Newtonsoft.Json.Linq.JObject.Parse(restResponse.Content);
dynamic jsonResponse = JsonConvert.DeserializeObject(restResponse.Content);
dynamic jsonResponse2 = JsonConvert.DeserializeObject<RootObject>(string JObject);`
Your response can be represented by classes like this:
public class Rootobject
{
public Feature[] features { get; set; }
public string type { get; set; }
public Crs crs { get; set; }
}
public class Crs
{
public string type { get; set; }
public Properties properties { get; set; }
}
public class Properties
{
public string name { get; set; }
}
public class Feature
{
public string type { get; set; }
public Geometry geometry { get; set; }
public Properties1 properties { get; set; }
}
public class Geometry
{
public string type { get; set; }
public object[][][] coordinates { get; set; }
}
public class Properties1
{
public string text { get; set; }
public int id { get; set; }
}
Hence your code can be changed to:
var restClient = new RestClient("https://cbsservis.tkgm.gov.tr/megsiswebapi.v2/api/idariYapi/ilListe");
var restRequest = new RestRequest(Method.GET);
var restResponse = restClient.Execute(restRequest);
restRequest.AddHeader("Accept", "text/json");
var obj = JsonConvert.DeserializeObject<Rootobject>(restResponse.Content);
You will receive the object like this:
And then you can loop through properties to get desired text.

Exporting class containing an ObservableCollection to csv in C#

I've found many solutions for exporting a class to CSV but my problem is this:
The class I'm trying to export has a property that is an observablecollection. eg:
public class ShipmentForExport
{
public string WaybillNumber { get; set; }
public DateTime WaybillDate { get; set; }
public string CustomerName { get; set; }
public string CustomerCode { get; set; }
public string CollectingBranchName { get; set; }
public string CollectingBranchCode { get; set; }
public string RecipientName { get; set; }
public string RecipientPhoneNumber { get; set; }
public string RecipientCellphoneNumber { get; set; }
public string RecipientCompany { get; set; }
public string DestinationAddress1 { get; set; }
public string DestinationAddress2 { get; set; }
public string DestinationCity { get; set; }
public string DestinationSuburb { get; set; }
public string DestinationProvince { get; set; }
public string DestinationCountry { get; set; }
public string DestinationPostalCode { get; set; }
***public ObservableCollection<InHouseParcel> Parcels { get; set; }***
}
When I try export a list of shipments to csv it works but obviously the parcels do not export the way I want them to.
I have tried using Filehelpers Library and csvHelper as well.
Any help is greatly appreciated!!
Josh's answer is outdated nowadays. You can use a typeconverter like:
CsvHelper.TypeConversion.TypeConverterFactory.AddConverter<ObservableCollection<string>>(new CsvHelper.TypeConversion.StringListConverter());
using (var txt = new StreamReader(filename))
using (var reader = new CsvHelper.CsvReader(txt))
{ .... }
namespace CsvHelper.TypeConversion
{
public sealed class StringListConverter : DefaultTypeConverter
{
public override object ConvertFromString(TypeConverterOptions options, string text)
{
var oc = new ObservableCollection<string>();
if (text.IndexOf('|') >= 0)
{
var list = text.Split('|').ToList<string>();// base.ConvertFromString(options, text);
oc = new ObservableCollection<string>(list);
}
return oc;
}
public override string ConvertToString(TypeConverterOptions options, object value)
{
var l = value as IEnumerable<string>;
if ( l == null || l.Count() == 0)
{
return "";
}
return string.Join("|", l);
}
public override bool CanConvertFrom(Type type)
{
return type == typeof(string);
}
}
}
Using CsvHelper (a library I maintain)...
When writing, you'll have to write manually because writing of collection properties isn't supported.
foreach( var record in records )
{
csv.WriteField( record.WaybillNumber );
...
foreach( var parcel in record.Parcels )
{
csv.WriteField( parcel );
}
}
Reading is a little easier because you can add it in the mapping.
Map( m => m.Parcels ).ConvertUsing( row =>
{
var oc = new ObservableCollection<InHouseParcel>();
var parcel = row.GetField<InHouseParcel>( 17 );
oc.Add( parcel );
} );
You'll need to convert the field values into InHouseParcel and loop through the remainder of the fields in the row. I'll leave that task to you.