CsvHelper mapping issue - csv

I have a question related to CsvHelper library and I cannot figure out how to map a csv file to the following MyClass object.
the csv file look like:
id, Property1, property2....
1, x, a,b,c
2,x, d,f
3, y, g,h,i,j,k
...
Which I would like to parse to the following classes
public class MyClass
{
public string Id { get; set; }
public List<Custom> MyCustoms { get; set; }
}
public class Custom
{
public string Property1 { get; set; }
public List<string> Property2 { get; set; }
}

ConvertUsing is going to be the easiest way to map this.
public class Program
{
static void Main(string[] args)
{
using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream))
using (var reader = new StreamReader(stream))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
writer.WriteLine("Id,Property1,Property2,Property3,Property4,Property5,Property6");
writer.WriteLine("1,x,a,b,c");
writer.WriteLine("2,x,d,f");
writer.WriteLine("3,y,g,h,i,j,k");
writer.Flush();
stream.Position = 0;
var test = csv.Configuration.RegisterClassMap<MyClassMap>();
var records = csv.GetRecords<MyClass>().ToList();
}
}
}
public class MyClassMap: ClassMap<MyClass>
{
public MyClassMap()
{
Map(m => m.Id);
Map(m => m.MyCustoms).ConvertUsing(row =>
{
var custom = new Custom
{
Property1 = row["Property1"],
Property2 = new List<string>()
};
var index = 2;
while (row.TryGetField(typeof(string), index, out var property))
{
custom.Property2.Add((string)property);
index++;
}
return new List<Custom> { custom };
});
}
}
public class MyClass
{
public string Id { get; set; }
public List<Custom> MyCustoms { get; set; }
}
public class Custom
{
public string Property1 { get; set; }
public List<string> Property2 { get; set; }
}

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; }
}
}

RestSharp query returning NotFound

This is my first usage of RestSharp
I am trying to connect to HubSpot using their FormsAPI (https://legacydocs.hubspot.com/docs/methods/forms/submit_form)
Using .Net, C#, MVC.
When I run in Fiddler, it works.
Here is my C# code, when I run it, I get a StatusCode of "NotFound". I am sure it is something simple I am missing?
var client = new RestClient("https://api.hsforms.com");
var request = new RestRequest("submissions/v3/integration/submit/{PortalId}/{formGuid}", Method.POST);
request.AddUrlSegment("portalId", "[myportalid]");
request.AddUrlSegment("formGuid", "[myformid]");
request.AddQueryParameter("hapikey", "[myapikey]");
request.RequestFormat = DataFormat.Json;
request.AddParameter("firstname", "testfirstname");
request.AddParameter("lastname", "testlastname");
request.AddParameter("email", "testemail#emailaddress.com");
request.AddParameter("business_unit", "Test");
It is better to create model of c# class and serialize it to Json and send POST request.
Example of RestSharp request
public async Task SendHubSpotRequest()
{
var PortalId = 1;
var formGuid = 1;
var client = new RestClient("https://api.hsforms.com");
var request = new RestRequest($"submissions/v3/integration/submit/{PortalId}/{formGuid}", Method.POST);
var hubSpotRequest = new HubSpotRequest()
{
SubmittedAt = "1517927174000",
Fields = new Field[]
{
new Field() { Name = "email", Value = "testemail#emailaddress.com" },
new Field() { Name = "firstname", Value = "testfirstname" },
new Field() { Name = "lastname", Value = "testlastname" }
},
Context = new Context
{
Hutk = "hutk",
PageUri = "www.example.com/page",
PageName = "Example page"
},
LegalConsentOptions = new LegalConsentOptions
{
Consent = new Consent
{
// Fill other params
}
}
};
request.AddParameter("application/json; charset=utf-8", JsonConvert.SerializeObject(hubSpotRequest), ParameterType.RequestBody);
var response = await client.ExecuteAsync(request);
var responseContent = response.Content;
}
C# classes of body json model
public class HubSpotRequest
{
[JsonProperty("submittedAt")]
public string SubmittedAt { get; set; }
[JsonProperty("fields")]
public Field[] Fields { get; set; }
[JsonProperty("context")]
public Context Context { get; set; }
[JsonProperty("legalConsentOptions")]
public LegalConsentOptions LegalConsentOptions { get; set; }
}
public class Context
{
[JsonProperty("hutk")]
public string Hutk { get; set; }
[JsonProperty("pageUri")]
public string PageUri { get; set; }
[JsonProperty("pageName")]
public string PageName { get; set; }
}
public class Field
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
}
public class LegalConsentOptions
{
[JsonProperty("consent")]
public Consent Consent { get; set; }
}
public class Consent
{
[JsonProperty("consentToProcess")]
public bool ConsentToProcess { get; set; }
[JsonProperty("text")]
public string Text { get; set; }
[JsonProperty("communications")]
public Communication[] Communications { get; set; }
}
public class Communication
{
[JsonProperty("value")]
public bool Value { get; set; }
[JsonProperty("subscriptionTypeId")]
public long SubscriptionTypeId { get; set; }
[JsonProperty("text")]
public string Text { get; set; }
}

Deserialize JSON data in to a class in c#

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

Json serialization in MVC

Below are my two model classes
public class ResponseData
{
public List<string> labels { get; set; }
public List<string> series { get; set; }
public List<dataForMetric> data{ get; set; }
}
public class dataForMetric
{
public List<int> value { get; set; }
}
and my action method is
public ActionResult GetData()
{
ResponseData res = new ResponseData();
res.labels = new List<string>() { "day1", "day2", "day3" , "day4"};
res.series = new List<string>() { "dummy" };
res.data = new List<dataForMetric>() { new dataForMetric() { value = new List<int>() {10} } ,
new dataForMetric() { value = new List<int>() {110} } ,
new dataForMetric() { value = new List<int>() {120} } ,
new dataForMetric() { value = new List<int>() {130} }
};
return Json(res, JsonRequestBehavior.AllowGet);
}
The JSON output of above action method is
{"labels":["day1","day2","day3","day4"],"series":["dummy"],"data":[{"value":[10]},{"value":[110]},{"value":[120]},{"value":[130]}]}
But for my requirement the output should be
{"labels":["day1","day2","day3","day4"],"series":["dummy"],"data":[[10],[110],[120],[130]]}
Please let me know how it can be achieved.
Well if you actually want output like you describe you should chenge your class to this:
public class ResponseData
{
public List<string> labels { get; set; }
public List<string> series { get; set; }
public int[][] data { get; set; }
}
I generate this class with VS 2013. It now has feature to create class structure from JSON. Edit -> Paste Special -> Pase JSON as classes. Hope this instrument will ease your life a lot.
Your dataForMetric class is unnecessary. You can achieve the desired result with a list of lists:
public class ResponseData
{
public List<string> labels { get; set; }
public List<string> series { get; set; }
public List<List<int>> data { get; set; }
}
public ActionResult GetData()
{
ResponseData res = new ResponseData();
res.labels = new List<string> { "day1", "day2", "day3" , "day4"};
res.series = new List<string> { "dummy" };
res.data = new List<List<int>> {
new List<int> { 10 },
new List<int> { 110 },
new List<int> { 120 },
new List<int> { 130 }
};
return Json(res, JsonRequestBehavior.AllowGet);
}
You must either define data as a single dataForMetric or define dataForMetric.value as a single int.
Your problem is you're instantiating a List of a List of int.

How to display polyline and markers on map based on JSON data? (Windows Phone)

I am able to draw the polyline on the map on the area that I have tapped on by the MapGesture event, however I would like to display the polyline based on my JSON data. Is there anybody that can give me some guidance how I can code it? Thank you!
public MainPage()
{
InitializeComponent();
Draw MyDrawObject = new Draw(MyMap)
{
FillSymbol = LayoutRoot.Resources["RedFillSymbol"] as FillSymbol
};
MyDrawObject.DrawComplete += MyDrawObject_DrawComplete;
MyDrawObject.DrawMode = DrawMode.Polyline;
MyDrawObject.IsEnabled = true;
// Create webclient.
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
client.DownloadStringAsync(new Uri("http://www.onemap.sg/publictransportation/service1.svc/routesolns?token=qo/s2TnSUmfLz+32CvLC4RMVkzEFYjxqyti1KhByvEacEdMWBpCuSSQ+IFRT84QjGPBCuz/cBom8PfSm3GjEsGc8PkdEEOEr&sl=530927&el=569830&startstop=&endstop=&walkdist=300&mode=bus&routeopt=cheapest&retgeo=true&maxsolns=1&callback="));
}
private void MyDrawObject_DrawComplete(object sender, ESRI.ArcGIS.Client.DrawEventArgs args)
{
Graphic graphic = new Graphic()
{
Geometry = args.Geometry,
Symbol = LayoutRoot.Resources["RedFillSymbol"] as FillSymbol
};
GraphicsLayer graphicsLayer = MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer;
graphicsLayer.Graphics.Add(graphic);
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
//base.OnNavigatedTo(e);
setUpLayers();
}
private void setUpLayers()
{
ArcGISTiledMapServiceLayer baseMapLayer = new ArcGISTiledMapServiceLayer();
baseMapLayer.ID = "BaseMap";
baseMapLayer.Url = "http://e1.onemap.sg/arcgis/rest/services/SM128/MapServer";
MyMap.Layers.Add(baseMapLayer);
}
public class STEP
{
//public string STEP { get; set; }
public string type { get; set; }
public string ServiceType { get; set; }
public string ServiceID { get; set; }
public string NumberOfStop { get; set; }
public string BoardId { get; set; }
public string BoardDesc { get; set; }
public string BoardDist { get; set; }
public string AlightId { get; set; }
public string AlightDesc { get; set; }
public string AlightDist { get; set; }
}
public class BusRoute
{
public string Solution { get; set; }
public string Duration { get; set; }
public string TotalCard { get; set; }
public string TotalCash { get; set; }
public string TotalDistance { get; set; }
public List<STEP> STEPS { get; set; }
public string TotalStops { get; set; }
public List<List<string>> PATH { get; set; }
}
public class RootObject
{
public List<BusRoute> BusRoute { get; set; }
}
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
var rootObject = JsonConvert.DeserializeObject<RootObject>(e.Result);
foreach (var route in rootObject.BusRoute)
{
string duration = route.Duration;
string totalStops = route.TotalStops;
//tb_test.Text = "Total Duration: " + duration;
//tb_test2.Text = "Total number of stops: " + totalStops;
}
}
private void MyMap_MapGesture(object sender, ESRI.ArcGIS.Client.Map.MapGestureEventArgs e)
{
if(e.Gesture == GestureType.Tap)
{
MapPoint point = new MapPoint(e.MapPoint.X,e.MapPoint.Y);
double x = point.X;
double y = point.Y;
var _polyline = new MapPolyline();
_polyline.StrokeColor = Colors.Blue;
_polyline.StrokeThickness = 2;
_polyline.Path.Add(new GeoCoordinate(x,y));
}
}
}
You would need to have a webapi (or any service) endpoint to connect to and retrieve the data. Once you get the data you will need to convert the DataTransfer Object into a GeoCoordinate object so that it can be added to the map:
MapPolyline line = new MapPolyline();
public void InsertCoordsToMap(IEnumerable<YourDtoClass> deSerializedJson) {
foreach(var item in deSerializedJson) {
GeoCoordinate elementToAdd = new GeoCoordinate(item.Latidude, item.Longitude);
map.Path.Add(elementToAdd);
}
}