3

I have a little program that fetches data from a web service. The program takes the JSON response, maps it to POCOs and writes the objects to a CSV file (automapping). It works perfectly when I ask for "all" the data in the dataset, however, if I query the resource (via OData) like this: "$select EmpNo, FirstName, LastName", the CSV writer will still write all of the columns to the CSV header, e.g. "EmpNo, FirstName, LastName, Street, Address, City, Age" etc. and just insert 0 (if int), false(if boolean) or "" (if string) to the columns that have no data.

The web service correctly returns only the specified columns, so that's not the issue. I use CsvHelper for the object mapping and CSV-writing. (But I'm open to using anything that can solve my problem)

I'd like to only write "EmpNo, FirstName, LastName" and the columns' data to the CSV-file, if that's what I ask for in the OData query.

Any good ideas for solving this?

1
  • Can you post some of your code? Commented Jul 31, 2015 at 14:18

2 Answers 2

3

It is hard to tell without knowing the exact code you're using. But my guess is that when you write your list of objects you're using the model that has the extra fields in it, which are all empty because you didn't request them via odata.

If you want just the subset with CsvHelper, you probably want to specify a CsvClassMap<T> and that will map your existing model into just the fields you want

There are lots of examples on a CsvClassMap here: http://joshclose.github.io/CsvHelper/

The write method will likely have a method overload that will take a classmap.

Sign up to request clarification or add additional context in comments.

2 Comments

Yep, I'm using the model which has all the fields in it. What data I want depends on what is specified in the query string (which changes all the time) so I need a way to do this at runtime.
search for Runtime Mapping in the link above
1

You can create a ClassMapper and specify which properties from the object you want to write (and how you want to write them!)
https://joshclose.github.io/CsvHelper/examples/configuration/class-maps/mapping-properties

Then when you go to write, just specify the ClassMapper

using (var writer = new StreamWriter("path\\to\\file.csv"))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
    csv.Configuration.RegisterClassMap<NameOfClassMapper>();
    csv.WriteRecords(records);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.