-
I need to send data to an api who accepts JSON and CSV. I'm asked that CSV headers must match JSON property naming policy var JsonSerializerOptions = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
}; I have created this small linqpad program void Main()
{
var jsonSerializerOptions = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
};
var p = new Person { Id = 1, FirstName = "John", LastName = "Doe" };
var json = JsonSerializer.Serialize(p, jsonSerializerOptions);
json.Dump();
using (var writer = new StringWriter())
using (var csv = new CsvWriter(writer,
new CsvConfiguration(CultureInfo.InvariantCulture) { LeaveOpen = true, HasHeaderRecord = true }))
{
csv.WriteHeader<Person>();
csv.NextRecord();
csv.WriteRecord(p);
csv.Flush();
var newRecord = writer.ToString();
newRecord.Dump();
}
}
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
} Which output this :
I tried creating an extension method on public static class CsvWriterExtensions
{
public static void WriteHeaderCamelCase<T>(this CsvWriter csv, CultureInfo cultureInfo = null)
{
cultureInfo = cultureInfo ?? CultureInfo.InvariantCulture;
foreach (var prop in typeof(T).GetProperties())
{
var pName = prop.Name;
csv.WriteField(Char.ToLower(pName[0], cultureInfo) + pName.Substring(1));
}
}
} The problem is that it doesn't work with anonymous types and does not support the CsvConfiguration class. I also tried to inherit from CsvWriter and override the Last thing, I cannot use ClassMap or Attributes because I don't know the object I will receive. Any idea on how to solve this issue ? Thanks |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
This piece of code made the job var mapType = typeof(DefaultClassMap<>).MakeGenericType(p.GetType());
var map = (ClassMap)ObjectResolver.Current.Resolve(mapType);
map.AutoMap(csv.Context);
foreach (var memberMap in map.MemberMaps)
{
memberMap.Data.Names.Add(System.Text.Json.JsonNamingPolicy.CamelCase.ConvertName(memberMap.Data.Member.Name));
}
csv.Context.RegisterClassMap(map); Are there any edge case am I missing with this ? |
Beta Was this translation helpful? Give feedback.
This piece of code made the job
Are there any edge case am I missing with this ?