3

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!

2
  • what about newtonsoft json? Commented Jul 9, 2018 at 15:45
  • Yes i tryed, but didn´t undesrstand... Could you help me with DataSet and DataTable ? This is, what i dont understand. Commented Jul 9, 2018 at 15:47

1 Answer 1

5

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"]);
}
Sign up to request clarification or add additional context in comments.

5 Comments

It works! Is there any way to get the number of rows?
simple way you can use for loop to count array then the index be your number.dotnetfiddle.net/UybCQ1 you can add the number in to your model
look like this. string jsonString2 = "[{\"id\": \"21\",\"date\": \"2018-01-01\",\"name\": \"Name1\"},{\"id\": \"22\",\"date\": \"2018-01-02\", \"name\": \"Name2\"}]";
If your string want to contain " double quotes another way you need to add \ before double quotes
Could you cancle your code on dotnetfiddle.net, so that i can take a look at the for loop again?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.