[Solved] [Newtonsoft.Json] Cannot deserialize my JSON ...

Franck_SDEAFranck_SDEA Member ✭✭

Hi devs !

I make my first mobile app with Xamarin.Forms. This app is connected to our Oracle DataBase with Rest Service.
Here is the error message:

My JSON result:

{
"items": [
{
"id_categorie": 1,
"label_categorie": "Situation dangereuse"
},
{
"id_categorie": 2,
"label_categorie": "Presqu'accident"
},
{
"id_categorie": 3,
"label_categorie": "Accident bénin"
},
{
"id_categorie": 4,
"label_categorie": "Accident de service"
},
{
"id_categorie": 5,
"label_categorie": "Accident de trajet"
},
{
"id_categorie": 6,
"label_categorie": "Incident Environnement"
}
]
}

And my C# code:

    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Net.Http;
    using Newtonsoft.Json;

    using Xamarin.Forms;
    using Xamarin.Forms.Xaml;

    namespace PackQSE_Mobile.Views
    {
        public class Categories
        {
            public string id_categorie { get; set; }
            public string label_categorie { get; set; }
        }

        [XamlCompilation(XamlCompilationOptions.Compile)]
        public partial class Declaration : ContentPage
        {
            // Liste des Url pour l'accès aux données :
            private const string UrlCategories = "http://my-serv:8080/ords/pack_epi/categories_accidents/type_accidents";

            // Autres variables privées pour les protocoles HTTP...
            private HttpClient _client = new HttpClient();
            private ObservableCollection<Categories> _categories;

            public Declaration ()
            {
                InitializeComponent ();
            }

            protected override async void OnAppearing()
            {
                base.OnAppearing();

                var contenu = await _client.GetStringAsync(UrlCategories);
                var categories = JsonConvert.DeserializeObject<List<Categories>>(contenu);

                _categories = new ObservableCollection<Categories>(categories);
                ListeCategories.ItemsSource = _categories;
            }
        }
    }

What should I do to make it work ?

Thanks a lot in advance.

Posts

  • AlessandroCaliaroAlessandroCaliaro ITMember ✭✭✭✭✭

    you should use this

    public class Item
    {
        public int id_categorie { get; set; }
        public string label_categorie { get; set; }
    }
    
    public class RootObject
    {
        public List<Item> items { get; set; }
    }
    
    var categories = JsonConvert.DeserializeObject<RootObject>(contenu);
    
  • Franck_SDEAFranck_SDEA Member ✭✭

    Nice, it work !!

    Thanks you ;)

Sign In or Register to comment.