I am working on deserialize json string using JavaScriptSerializer in C#, and trying to parse the json string and map it to the appropriate columns in the sql server table for inserting data. I have the sample json string as below.
JSON
{
"event": [
[
{
"Id": 456895,
"Name": "Chelsea - Arsenal",
"BetOffers": [
{
"BetType": "Game",
"Picks": [
{
"Pick": "1",
"Odds": 1.15
},
{
"Pick": "x",
"Odds": 1.46
},
{
"Pick": "2",
"Odds": 1.15
}
]
}
]
}
],
[
{
"Id": 456879,
"Name": "Liverpool - Manchester United",
"BetOffers": [
{
"BetType": "Game",
"Picks": [
{
"Pick": "1",
"Odds": 1.20
},
{
"Pick": "x",
"Odds": 1.42
},
{
"Pick": "2",
"Odds": 1.85
}
]
}
]
}
]
]
}
Based on the json output string I am writing my class in C# as below.
Classes
public class Event
{
public int Id { get; set; }
public string Name { get; set; }
public List<BetOffer> BetOffers { get; set; }
}
public class BetOffer
{
public string BetType { get; set; }
public List<BetPick> Picks { get; set; }
}
public class BetPick
{
public string Pick { get; set; }
public double Odds { get; set; }
}
public class MyRootObject
{
public List<List<BetPick>> @event { get; set; }
}
var root = new JavaScriptSerializer().Deserialize<MyRootObject>(jsonString);
Insert data into the table as following.
string connectionString = "Database ConnectionString";
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("ID", typeof(string)));
dt.Columns.Add(new DataColumn("Name", typeof(string)));
dt.Columns.Add(new DataColumn("BetType", typeof(string)));
dt.Columns.Add(new DataColumn("Pick", typeof(string)));
dt.Columns.Add(new DataColumn("Odds", typeof(string)));
DataRow dr = dt.NewRow();
for (var i = 0; i < root.event.Count; i++)
{
dr = dt.NewRow();
dr["ID"] = root.event[i].Id;//stuck at table to json string parse and map
dt.Rows.Add(dr);
}
Question
I'm stuck with how to parse json string and map data to appropriate columns in the table for inserting data into a sql table. Unable to find root.event.Id from the json string?
Error
List does not contain definition for Id
>' which ultimately is a list which does not contain a definition for Id. Try making your root object something that has an Id per row. Have a look at https://stackoverflow.com/questions/51140749/cant-list-table-from-sql-to-mvc-view as well. It might help.
– openshac Nov 20 '20 at 07:26