Reputation: 579
I am now working on a Xamarin project and I am using Firebase as my database.
I have a set of data as following:
I have managed to retrieve the data via RESTful service. However, when I tried to JsonConvert.Deserialize
them, I am faced with an error telling me that I cannot convert to .NET Collection
.
Is there a way I can do it?
My Model
public class TodoItem
{
public string ID { get; set; }
public string Name { get; set; }
public string Notes { get; set; }
public bool Done { get; set; }
}
Retrieving from RESTful service
public async Task<List<TodoItem>> RefreshDataAsync()
{
Items = new List<TodoItem>();
//RestUrl = refer to constants.cs
var uri = new Uri(string.Format(Constants.RestUrl, string.Empty));
try
{
var response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
Items = JsonConvert.DeserializeObject<List<TodoItem>>(content);
}
}
catch (Exception ex)
{
Debug.WriteLine(@" ERROR{0}", ex.Message);
}
return Items;
}
UI
listView.ItemsSource = await App.TodoManager.GetTasksAsync();
Update
What's in the content of variable content
{\"-L9K-8AF9fxZfe6bwTjk\":{\"Done\":false,\"ID\":\"323642ac-89e2-4f14-b9b0-e9b7306aee81\",\"Name\":\"ufhd\",\"Notes\":\"nvnv\"},\"-L9K07oNjtvPQYbdyItU\":{\"Done\":false,\"ID\":\"c7a53ad2-533f-454c-9ac0-5b21c3d2669c\",\"Name\":\"abc\",\"Notes\":\"cde\"},\"-L9K1n1r7Q7ZIgA3KFaD\":{\"Done\":false,\"ID\":\"938bd62f-f117-4733-a1e4-a4ed22233ca3\",\"Name\":\"ffef\",\"Notes\":\"dfg\"}}
Upvotes: 1
Views: 759
Reputation: 1756
This is more of a complement to Evk's answer.
I have taken the liberty of minifying your example dataset for the sake of brevity. This little example I have verified for the functionality.
class Program
{
static void Main(string[] args)
{
var JSONStr = "{\"user\":{\"L9k0\":{\"ID\":\"001\", \"name\":\"somename\"},\"L9k1\":{\"ID\":\"002\", \"name\":\"someothername\"}}}";
var res = JsonConvert.DeserializeObject<JsonResult>(JSONStr);
Console.ReadLine();
}
}
class JsonResult {
public Dictionary<string, ToDoItem> user { get; set; }
}
class ToDoItem {
public string ID { get; set; }
public string name { get; set; }
}
Upvotes: 1
Reputation: 101563
As you can see from both first screenshot and from your json string - json you receive does not actually represent a collection. It's an object with cryptic properties, each property represents one todo item.
So you need to deserialize it as dictionary:
JsonConvert.DeserializeObject<Dictionary<string, TodoItem>>(content);
If you don't care about those cryptic property names, you can do:
Items = JsonConvert.DeserializeObject<Dictionary<string, TodoItem>>(content).Values.ToList()
Upvotes: 6