I have a json data like this coming through the API.
{
"getDataJSON": {
"message": "",
"tables": [
{
"rows": [
{
"cols": [
{
"colName": "columnName1",
"colValue": "columnValue"
},
{
"colName": "columnName2",
"colValue": "columnValue"
}
]
},
{
"cols": [
{
"colName": "columnName1",
"colValue": "columnValue"
},
{
"colName": "columnName2",
"colValue": "columnValue"
}
]
}
]
}
]
}
}
I deserialize this data. But using nested loops. How can i deserialize more effectively? Any ideas?
I deserialize like this;
var jsonData = JsonConvert.DeserializeObject<Root>(response.Content);
foreach (Row item in jsonData.GetDataJSON.tables[0].rows)
{
Model nodeModel = new Model();
foreach (Col itemCol in item.cols)
{
if (itemCol.colName == "columnName" && !string.IsNullOrEmpty(itemCol.colValue))
nodeModel.columnName = itemCol.colValue;
else if (itemCol.colName == "columnName" && !string.IsNullOrEmpty(itemCol.colValue))
nodeModel.columnName = itemCol.colValue;
}
returnModel.Add(nodeModel);
}
thank you everyone.
Try this
var tables = (JArray)JObject.Parse(json)["getDataJSON"]["tables"];
DataSet ds = new DataSet();
for (var i = 0; i < tables.Count; i++)
{
var rows = (JArray)tables[i]["rows"];
DataTable dt = JArray.FromObject(rows.Select(r => CreateJobject((JArray)r["cols"])))
.ToObject<DataTable>();
ds.Tables.Add(dt);
}
public JObject CreateJObject(JArray jArr)
{
var jObj = new JObject();
foreach (var c in jArr)
jObj.Add((string)c["colName"], c["colValue"]);
return jObj;
}