I’m trying to convert a json input format into another json format by using c#.
The input format which is seen just below is gotten from a httpclient post request:
{
"data": {
"trafficData": {
"volume": {
"byHour": {
"edges": [
{
"node": {
"from": "2019-10-24T12:00:00+02:00",
"to": "2019-10-24T13:00:00+02:00",
"byDirection": [
{
"heading": "North",
"total": {
"volumeNumbers": {
"volume": 696
}
}
},
{
"heading": "South",
"total": {
"volumeNumbers": {
"volume": 726
}
}
}
]
}
},
{
"node": {
"from": "2019-10-24T13:00:00+02:00",
"to": "2019-10-24T14:00:00+02:00",
"byDirection": [
{
"heading": "North",
"total": {
"volumeNumbers": {
"volume": 805
}
}
},
{
"heading": "South",
"total": {
"volumeNumbers": {
"volume": 751
}
}
}
]
}
}
]
}
}
}
}
}
I wish to transform the json input to something similar to the output code just below:
{
"data":[
{
"from":"2019-10-24T12:00:00+02:00",
"to":"2019-10-24T13:00:00+02:00",
"heading":"South",
"volume":726
},
{
"from":"2019-10-24T13:00:00+02:00",
"to":"2019-10-24T14:00:00+02:00",
"heading":"South",
"volume":751
}
]
}
In c# i have tried the below code: (also in connection with creating new class objects with https://json2csharp.com/)
//o1 is the json object input
IEnumerable<JToken> jTokens = o1.Descendants().Where(p => !p.HasValues);
Dictionary<string, string> results = jTokens.Aggregate(new Dictionary<string, string>(), (properties, jToken) =>
{
properties.Add(jToken.Path, jToken.ToString());
return properties;
});
2
Answers
try this code
I would personally use AutoMapper in this case.
My answer will be written using .NET 6 Web API model (with AutoMapper package obviously installed first).
I generated the C# classes with the tool you provided for my example.
Let’s assume I have a Request.cs file as :
Using your tool, I also created a Response.cs like this :
In order to handle mapping between the two type of objects, I would create a MappingConfiguration like so :
In my Program.cs, I would then Dependency Inject my MappingConfiguration with code below, before my "builder.Build()" :
Finally, within my business class, I can do something like this:
Hope this gives you an alternative.