Reputation: 199
I´ve searched for a long time but without success...
I want to parse a json response from an API in Xamarin.Android.
My json responsee is like this:
[
{
"id": "21",
"date": "2018-01-01",
"name": "Name1"
},
{
"id": "22",
"date": "2018-01-02",
"name": "Name2",
}
]
As you see, it contains 2 rows. The numer of rows can change. Sometimes the there are 6 rows but sometimes only 2...
So i want to get the value of each id, date and name tag, for each row. I tryed with an for each loop but don't succeed...
Could someone help me with DataSet and DataTable?
I saw this code but get an error with DataSet and DataTable:
string json = @"{
'Table1': [
{
'id': 0,
'item': 'item 0'
},
{
'id': 1,
'item': 'item 1'
}
]
}";
DataSet dataSet = JsonConvert.DeserializeObject<DataSet>(json);
DataTable dataTable = dataSet.Tables["Table1"];
Console.WriteLine(dataTable.Rows.Count);
// 2
foreach (DataRow row in dataTable.Rows)
{
Console.WriteLine(row["id"] + " - " + row["item"]);
}
// 0 - item 0
// 1 - item 1
Thank you in advance!
Upvotes: 3
Views: 2828
Reputation: 46219
You can use Json.net JsonConvert.DeserializeObject
function
Make a ObjModel
class to carry your json data.
public class ObjModel
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("date")]
public string Date { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}
ObjModel[] datas = JsonConvert.DeserializeObject<ObjModel[]>(jsonData);
c# online:https://dotnetfiddle.net/UybCQ1
if you want to DeserializeObject
to DataTable
it can work too.
DataTable dt = JsonConvert.DeserializeObject<DataTable>(jsonString2);
foreach(DataRow row in dt.Rows){
Console.WriteLine(row["id"]);
}
Upvotes: 5