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.
Related
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();
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);
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
I have the following classes that I'm using to collect data and then return the structure in Json.
public class Outcome {
public int id { get; set; }
public string outcome { get; set; }
public string actionStep { get; set; }
public List<OutcomeActionResult> actionResults { get; set; }
public void setData(SqlDataReader reader, DateData dateData) {
this.id = Convert.ToInt32(reader["id"]);
this.outcome = Convert.ToString(reader["outcome"]);
this.actionStep = Convert.ToString(reader["action_step"]);
this.actionResults = new Outcomes().getActionResultByOutcomeId(this.id, dateData);
}
}
public class OutcomeActionResult {
public int id { get; set; }
public string actionResult { get; set; }
public ActionResultQuestion question { get; set; }
public void setData(SqlDataReader reader, DateData dateData) {
this.id = Convert.ToInt32(reader["id"]);
this.actionResult = Convert.ToString(reader["action_result"]);
this.question = new Outcomes().getActionResultQuestionByActionResultId(this.id, dateData);
}
}
public class ActionResultQuestion {
public int id { get; set; }
public string question { get; set; }
public bool isMultipleChoice { get; set; }
public List<MultipleChoiceOption> multipleChoiceOptions { get; set; }
ActionResultAnswer answer { get; set; }
public void setData(SqlDataReader reader, DateData dateData) {
this.id = Convert.ToInt32(reader["id"]);
this.question = Convert.ToString(reader["question"]);
this.isMultipleChoice = Convert.ToBoolean(reader["is_multi"]);
this.answer = new Outcomes().getActionResultAnswersByIdAndDate(this.id, dateData.year, dateData.month, dateData.day, dateData.shiftId);
}
}
public class ActionResultAnswer {
public int id { get; set; }
public string notes { get; set; }
public int employeeId { get; set; }
public int selectedAnswer { get; set; }
public string answer { get; set; }
public int year { get; set; }
public int month { get; set; }
public int day { get; set; }
public int shiftId { get; set; }
public void setData(SqlDataReader reader) {
this.id = Convert.ToInt32(reader["id"]);
this.notes = Convert.ToString(reader["notes"]);
this.employeeId = Convert.ToInt32(reader["employee_id"]);
this.selectedAnswer = reader.IsDBNull(reader.GetOrdinal("selected_answer")) ? -1 : Convert.ToInt32(reader["selected_answer"]);
this.answer = Convert.ToString(reader["answer"]);
this.year = Convert.ToInt32(reader["year"]);
this.month = Convert.ToInt32(reader["month"]);
this.shiftId = Convert.ToInt32(reader["shift_id"]);
}
}
As you can see, I have Outcome which contains a list of OutcomeActionResults each of which contains an ActionResultQuestion which has an ActionResultAnswer. Something like this:
Outcome -> List(OutcomeActionResult) --> ActionResultQuestion --> ActionResultAnswer
When I step through the code, all the data is being populated correctly and everything is fine. However, when I serialize the object structure to JSON it serializes everything except the ActionResultAnswer. Basically the deepest level of the structure gets chopped off. I've been unable to find anything that tells me why this is happening or how to have it not happen.
Probably ought to put the code that serializes the objects up here:
var response = outcomes.getOutcomesByClientAndDate(clientId, year, month, day, shiftId, dayOfWeek);
var json = JsonConvert.SerializeObject(response);
The answer property in your ActionResultQuestion class is not public. Therefore, it will not be serialized by Json.Net by default.
You can either make the property public...
public ActionResultAnswer answer { get; set; }
or, if you intend that it not be public, you can mark it with a [JsonProperty] attribute to allow the serializer to "see" it:
[JsonProperty]
ActionResultAnswer answer { get; set; }
i need to deserialize this.
{"previous_cursor_str":"0","next_cursor":0,"ids":[741999686,240455509,126524150,143548100,124328422,624776268,393738125,587829914,280834485,64818350,282713007,90425850,759794,164401208,114771958,114364910,89725893],"previous_cursor":0,"next_cursor_str":"0"}
any idea?
Its a JObject really with an array of Id's inside it.
First you can create a class to represent the json like this:
public class RootObject
{
public string previous_cursor_str { get; set; }
public int next_cursor { get; set; }
public List<int> ids { get; set; }
public int previous_cursor { get; set; }
public string next_cursor_str { get; set; }
}
Then to deserialize the json into the object you do this:
var myJsonObject = JsonConvert.DeserializeObject<RootObject>(jsonString);
Or if you just want the ids in a array:
var obj = JObject.Parse(jsonstring);
var idArray = obj["ids"].Children().Select(s=>s.value<string>());
Just tried https://jsonclassgenerator.codeplex.com/ and got the code below. Which is qhite the same as geepie's class. nice tool.
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Example
{
class Result
{
[JsonProperty("previous_cursor_str")]
public string PreviousCursorStr { get; set; }
[JsonProperty("next_cursor")]
public int NextCursor { get; set; }
[JsonProperty("ids")]
public IList<int> Ids { get; set; }
[JsonProperty("previous_cursor")]
public int PreviousCursor { get; set; }
[JsonProperty("next_cursor_str")]
public string NextCursorStr { get; set; }
}
public static unsafe void Main()
{
Result result = JsonConvert.DeserializeObject<Result> (" ... your string ...");
Console.WriteLine(result);
}
}