Description:
I am developing a web solution in c# asp.net so that, from the front, I can build a JSON
complex object so that, when it is received in the back, it saves the values in a SQL Server 2012 database.
The JSON
complex object is composed as follows:
[{
"__KEY__": "73c14f5b-cbb9-8711-217a-a1a5453b7159",
"sUserID": [80417452, 80426837, 79945118],
"FechaInicio": "2017-04-19T05:00:00.000Z",
"FechaFin": "2017-04-20T05:00:00.000Z",
"Id_Franja": 3
}]
Using the following lines to serialize the JSON object and convert it to DataTable
I get this result:
Code:
// La variable "myJson" contiene el JSON complejo.
DataTable jsonDataTable = (DataTable)JsonConvert.DeserializeObject(myJson, (typeof(DataTable)));
Serialization result:
I need to convert this complex JSON to a DataTable in C#; in this case, I need the values of the "sUserID" column to be in the DataTable
as a comma separated string.
How to convert this complex JSON object to a DataTable?
I have tried these solutions , but I am unable to adjust the code to achieve this goal.
I'm looking for other options to convert complex JSON objects "like the one in the example" to a DataTable.
The element
sUserID
is displayed in this way since the compiler itself determines the type and detects that it is aarray
ofint64[]
, and since it cannot display the content, it only displays the data type.If that value could come as
"sUserID": "[80417452, 80426837, 79945118]"
, then you can determine it as astring
.Now, before deserializing it directly to a
DataTable
, it is better to convert it to aList<T>
, so that from that list we handle it as the data source.Class definition:
Note that by not being able to convert
sUserID
directly tostring
we will rely on another variable calledsUserIdNuevo
and what it will do is concatenate the valuesarray
ofint64[]
withString.Join("", new List<int>(this.sUserID).ConvertAll(i => i.ToString()).ToArray());
Given your comment that you only use the
DataTable
to loop through it and use it as a variable for storage to the database, I suggest you loop through the list and that would suffice:This article points out 7 powerful reasons to switch to
DataTable
generic collections.