Json array parsing as observable collection

Nani_777Nani_777 INMember ✭✭

Could someone help me with this?
I want to deserialize my json array into an observable collection

Best Answers

Answers

  • TamerAlmurTamerAlmur USMember ✭✭✭

    You can use Newtonsoft.Json package, install it from NuGet

    var DeserializejsonObservable = JsonConvert.DeserializeObject<ObservableCollection<ClassName>>(GeneralResponse);
    
  • AlessandroCaliaroAlessandroCaliaro ITMember ✭✭✭✭✭

    Post your JSON

  • Nani_777Nani_777 INMember ✭✭

    This is my JSON Example

    {
        "TopLevelDomainList": {
            "DomainName": "List of Domains",
            "APIVersion": "1.0",
            "ListVersion": "1.1",
            "ListVersionDate": "19/12/2016 02:07:50",
            "ParticipatingDomains": [
                {
                    "Id": "2015-0001",
                    "DomainName": "ABC",
                    "Location": "http://www.something.com",
                    "Icon": "url"
    },
                {
                    "Id": "2015-0002",
                    "DomainName": "EFG",
                    "Location": "http://www.something.com",
                    "Icon": "url"
    },
                {
                    "Id": "2016-0001",
                    "DomainName": "HIF",
                    "Location": "http://www.something.com",
                    "Icon": "url"
    }
    
    ]
        }
    }
    
  • NMackayNMackay GBInsider, University mod

    @AlessandroCaliaro

    Not sure why observable collection is been used if it's a single object with a list of domains looking at it again.

  • Nani_777Nani_777 INMember ✭✭

    @AlessandroCaliaro @NMackay

    How could I bind it to my list view?

  • NMackayNMackay GBInsider, University mod

    Read the documentation and the sections on data binding before asking these questions if possible.

    https://developer.xamarin.com/guides/xamarin-forms/user-interface/listview/data-and-databinding/

  • JassimRahmaJassimRahma USMember ✭✭✭✭
    edited February 2018

    I have the same question questions guys..

    How can I bind the daily or weekly or monthly?

    I tried this but did not work:

            public class ActiveDeviceCount
            {
                public string datetime { get; set; }
                public int count { get; set; }
            }
    

    and here I am reading the data:

    var client = new HttpClient();
    client.BaseAddress = new Uri("https://api.appcenter.ms/v0.1/apps/xxxxxxx/xxxxxxxxx/analytics/active_device_counts?start=2018-01-19T12%3A23%3A39.000Z&end=2018-02-19T12%3A23%3A39.000Z");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    client.DefaultRequestHeaders.Add("X-API-Token", "xxxxxxxxxxxxxxxxxxxxx");
    HttpResponseMessage response = await client.GetAsync("https://api.appcenter.ms/v0.1/apps/xxxxxx/xxxxxxxx/analytics/active_device_counts?start=2018-01-19T12%3A23%3A39.000Z&end=2018-02-19T12%3A23%3A39.000Z");
    
    if (response.IsSuccessStatusCode)
    {
        var data = await response.Content.ReadAsStringAsync();
        // dynamic itemdata = JsonConvert.DeserializeObject(data);
        var result = JsonConvert.DeserializeObject<List<ActiveDeviceCount>>(data);
        ObservableCollection<ActiveDeviceCount> trends = new ObservableCollection<ActiveDeviceCount>(result);
    }
    else
    {
        // await DisplayAlert("else", response.StatusCode.ToString(), "Ok");
    }
    

    My json is like this:

    {
      "daily": [
        {
          "datetime": "2018-01-19T00:00:00Z",
          "count": 2
        },
        {
          "datetime": "2018-01-20T00:00:00Z",
          "count": 1
        },
        {
          "datetime": "2018-01-21T00:00:00Z",
          "count": 0
        },
        {
          "datetime": "2018-01-22T00:00:00Z",
          "count": 1
        }
      ],
      "weekly": [
        {
          "datetime": "2018-01-19T00:00:00Z",
          "count": 2
        },
        {
          "datetime": "2018-01-20T00:00:00Z",
          "count": 2
        },
        {
          "datetime": "2018-01-21T00:00:00Z",
          "count": 2
        }
      ],
      "monthly": [
        {
          "datetime": "2018-01-19T00:00:00Z",
          "count": 2
        },
        {
          "datetime": "2018-01-20T00:00:00Z",
          "count": 2
        },
        {
          "datetime": "2018-01-21T00:00:00Z",
          "count": 2
        },
        {
          "datetime": "2018-01-22T00:00:00Z",
          "count": 2
        }
      ]
    }
    
  • AlessandroCaliaroAlessandroCaliaro ITMember ✭✭✭✭✭

    @JassimRahma these should be your models

    public class Daily
    {
        public DateTime datetime { get; set; }
        public int count { get; set; }
    }
    
    public class Weekly
    {
        public DateTime datetime { get; set; }
        public int count { get; set; }
    }
    
    public class Monthly
    {
        public DateTime datetime { get; set; }
        public int count { get; set; }
    }
    
    public class RootObject
    {
        public List<Daily> daily { get; set; }
        public List<Weekly> weekly { get; set; }
        public List<Monthly> monthly { get; set; }
    }
    
  • JassimRahmaJassimRahma USMember ✭✭✭✭

    I tried that but getting:

    Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Wise.Analytics+RootObject]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
    To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
    Path 'daily', line 1, position 9.
      at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, System.Object existingValue) [0x00397] in <d035a66864a842de9ec4c9e5b4b8c188>:0
      at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, System.Object existingValue) [0x0006d] in <d035a66864a842de9ec4c9e5b4b8c188>:0
      at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType, System.Boolean checkAdditionalContent) [0x000db] in <d035a66864a842de9ec4c9e5b4b8c188>:0
      at Newtonsoft.Json.JsonSerializer.DeserializeInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType) [0x00054] in <d035a66864a842de9ec4c9e5b4b8c188>:0
      at Newtonsoft.Json.JsonSerializer.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType) [0x00000] in <d035a66864a842de9ec4c9e5b4b8c188>:0
      at Newtonsoft.Json.JsonConvert.DeserializeObject (System.String value, System.Type type, Newtonsoft.Json.JsonSerializerSettings settings) [0x0002d] in <d035a66864a842de9ec4c9e5b4b8c188>:0
      at Newtonsoft.Json.JsonConvert.DeserializeObject[T] (System.String value, Newtonsoft.Json.JsonSerializerSettings settings) [0x00000] in <d035a66864a842de9ec4c9e5b4b8c188>:0
      at Newtonsoft.Json.JsonConvert.DeserializeObject[T] (System.String value) [0x00000] in <d035a66864a842de9ec4c9e5b4b8c188>:0
      at Wise.Analytics+<show>d__5.MoveNext () [0x00238] in /Users/jassim/Projects/Wise/Wise/Analytics.xaml.cs:62
      at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Library/Frameworks/Xamarin.iOS.framework/Versions/11.6.1.4/src/mono/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:152
      at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__6_0 (System.Object state) [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/11.6.1.4/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/AsyncMethodBuilder.cs:1018
      at UIKit.UIKitSynchronizationContext+<Post>c__AnonStorey0.<>m__0 () [0x00000] in /Users/builder/data/lanes/5665/db807ec9/source/xamarin-macios/src/UIKit/UIKitSynchronizationContext.cs:24
      at Foundation.NSAsyncActionDispatcher.Apply () [0x00000] in /Users/builder/data/lanes/5665/db807ec9/source/xamarin-macios/src/Foundation/NSAction.cs:163
      at at (wrapper managed-to-native) UIKit.UIApplication:UIApplicationMain (int,string[],intptr,intptr)
      at UIKit.UIApplication.Main (System.String[] args, System.IntPtr principal, System.IntPtr delegate) [0x00005] in /Users/builder/data/lanes/5665/db807ec9/source/xamarin-macios/src/UIKit/UIApplication.cs:79
      at UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x00038] in /Users/builder/data/lanes/5665/db807ec9/source/xamarin-macios/src/UIKit/UIApplication.cs:63
      at Wise.iOS.Application.Main (System.String[] args) [0x00001] in /Users/jassim/Projects/Wise/iOS/Main.cs:17
    

    and my code is:

    var client = new HttpClient();
    client.BaseAddress = new Uri("https://api.appcenter.ms/v0.1/apps/xxxxxx/xxxxx/analytics/active_device_counts?start=2018-01-19T12%3A23%3A39.000Z&end=2018-02-19T12%3A23%3A39.000Z");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    client.DefaultRequestHeaders.Add("X-API-Token", "xxxxxxxxxxxx");
    HttpResponseMessage response = await client.GetAsync("https://api.appcenter.ms/v0.1/apps/xxxxxx/xxxxx/analytics/active_device_counts?start=2018-01-19T12%3A23%3A39.000Z&end=2018-02-19T12%3A23%3A39.000Z");
    
    if (response.IsSuccessStatusCode)
    {
        var data = await response.Content.ReadAsStringAsync();
        await App.Current.MainPage.DisplayAlert("result", Convert.ToString(data), "ok");
        var result = JsonConvert.DeserializeObject<List<RootObject>>(data);
    
        ObservableCollection<RootObject> trends = new ObservableCollection<RootObject>(result);
    }
    else
    {
        // await DisplayAlert("else", response.StatusCode.ToString(), "Ok");
    }
    

    Here is the result screenshot:

  • AlessandroCaliaroAlessandroCaliaro ITMember ✭✭✭✭✭
    edited February 2018
    var result = JsonConvert.DeserializeObject<List<RootObject>>(data);
    

    should be

    var result = JsonConvert.DeserializeObject<RootObject>(data);
    
  • MuthuMuthu Member ✭✭

    Binding Does not work . here the code

    Mainpage.cs

    HttpClient client = new HttpClient(); var response = await client.GetAsync(string.Format("uri link")); string jsonstring = await response.Content.ReadAsStringAsync(); RootObject item = JsonConvert.DeserializeObject<RootObject>(jsonstring); titles.ItemsSource =item.ToString();

    Mainpage.xaml

    <ListView x:Name="titles" HasUnevenRows="False" > <ListView.ItemTemplate> <DataTemplate> <ViewCell> <ViewCell.View> <StackLayout Orientation="Horizontal"> <Label Text="{Binding note}"/> </StackLayout> </ViewCell.View> </ViewCell> </DataTemplate> </ListView.ItemTemplate> </ListView>

    myclass

                `public class Result
                {
                    public string note { get; set; }
                }
                public class Response
                {
                    public List<Result> results { get; set; }
                }
                public class RootObject
                {
                    public Response response { get; set; }
                }`
    

    jsonstring:

    { "response": { "results": [ { "Created By": "non_authenticated_user_live", "Created Date": "2018-03-05T08:34:04.631Z", "Modified Date": "2018-03-05T08:34:04.677Z", "note": "hi", "_id": "1520238844627x475879674311727300", "_type": "custom.note" } ] } }

Sign In or Register to comment.