I am calling vendor Api to get json data, I want to convert that json to my custom structure.
Here is example
When I call student data, vendor returns data as below
{
"Students": [
{
"FirstName":"Abc",
"LastName":"pqr"
},
{
"FirstName":"pqr",
"LastName":"pqccr"
}
]
}
When I call employee data, it returns as below
{
"Employee": [
{
"FName":"Abc",
"LName":"pqr"
},
{
"FName":"pqr",
"LName":"pqccr"
}
]
}
I want to convert this to my own json format so that it would be easy to retrieve and manipulation something as below
{
"Person": [
{
"First_Name":"Abc",
"Last_Name":"pqr"
},
{
"First_Name":"pqr",
"Last_Name":"pqccr"
}
]
}
I am using system.text.json to serialized and deserialize.
How can I convert to this common structure?
Trying with system.text.json to deserialize but don’t have any idea on how can I convert to common structure
3
Answers
convert json objects to model and use addrange to assign the data. Tried an example as below.
Consider test1 class as students and test2 as employee
I would recommend to deserialize data to dedicated types (
StudentsResponse
andEmployeeResponse
for example) and map them to desired one (PersonHolder
for example) and then work with that type (serialize, manipulate, etc).If for some reason you don’t want to do that you can look into the
JsonNode
APIs to dynamically manipulate JSON. For example handling can look something like the following (possibly should be split into 2 branches):Data:
There are multiple approaches to solve this task. The best option depends on the context:
In the generic case, I would define some interface like:
And implement it for each of the data sources (e.g.
StudentReader
andEmployeeReader
).While you have the same structure with just different property names, you can have shared implementation like:
And just reuse it for your cases:
This way you can be flexible about implementations: you don’t duplicate much code while the structure is the same and in case one of the sources will change its format, you can just update corresponding class to whatever code you want (e.g. define custom models within that class or do any other logic).