I have the below Json to my API – can you please suggest me how do I store these json data in to C# List or collection
{
"AccountDetails": [
{
"InNumber": "123453333",
"OutNumber": "125666666"
},
{
"InNumber": "2345543334",
"OutNumber": "4556666667"
},
{
"InNumber": "9793543333",
"OutNumber": "2345543333"
}
]
}
I have tried below , but it snot working , kindly let me know if there is any better performance approach
var persons = JsonConvert.DeserializeObject<List<Member>>(AccountDetails);
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("InNumber", typeof(System.String)));
dt.Columns.Add(new DataColumn("OutNumber", typeof(System.String)));
foreach (var item in persons)
{
DataRow dr = dt.NewRow();
dr["InNumber"] = item.InNumber;
dr["OutNumber"] = item.OutNumber;
dt.Rows.Add(dr);
}
3
Answers
if you want a DataTable
if you want a List
The JSON you’ve shown is an Object with a Property called AccountDetails that contains your array. Note how the outer Json is surrounded by { } and not [ ] which is why you’re seeing that error.
This is a duplicate of Deserialize Json into C# Collection
You could solve that, for instance, like this:
working example
or you parse the collection out of the JSON Object (the answer below)
Create an object that contains a list of AccountDetails
deserialize to that
https://dotnetfiddle.net/NXCrDC
This is an elaboration of my comment.
Here I create a class to hold your account details:
But, your JSON data represents an object that has a single property that represents a collection of these, so I need this as well:
Now I can deserialize your data into an
Account
instance:In a reply comment to my comment, you say " I am able to list the all inNumbers and outnumbers in a list but it’s difficult to identify which is InNumber is tagged to Outnumber – can you please help me, how do I display records – such way that both the associated numbers can be easily identified , because at the end I need to to store InNumber and corresponding Outnumber in DB"
I’m not quite following. You have a list of
AccountDetail
objects, each of which has anInNumber
/OutNumber
pair. That’s easily inserted into a database using any modern database access mechanism (or, just a loop around anINSERT
statement). You don’t show your database access code, so I can’t tell you.What I can tell you is that I nearly never use DataTables unless I’m working on really old code.
Since it appears you really want it in a
DataTable
, add this code to the end ofTest
(after the line that startsvar result =
):