Convert JSON Array To List <> For ListView

kyiyerkyiyer Member ✭✭

Hi

New to classes (OOP) and Xamarin. Trying to learn as I go along.
Have a JSON array - being retrieved correctly from URL.
Here is a snippet. There will be multiple rows under response

{
"status":200,
"response":[
{
"id":"xxxxxxx",
"type":"News",
"subType":"Article",
"content_type":"0",
"title":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"shortTitle":"yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy",
"shortUrl":"https:\/\/qq.ww\/nuWqsg",
"imageThumb":"https:\/\/img.eee.com\/story\/rrrrrr.jpeg",
"date":"Oct 21, 2019 | 10:26",
"categoryName":"rrrrrrrr",
"sub_cat_name":"",
"sub_sub_cat_name":"",
"alias":"this_is_an_alias",
"fullUrl":"https:\/\/www.nothing.com"
},

I created two classes

public class Story
{
    public string id { get; set; }
    public string type { get; set; }
    public string subType { get; set; }
    public string content_type { get; set; }
    public string title { get; set; }
    public string shortTitle { get; set; }
    public string shortUrl { get; set; }
    public string imageThumb { get; set; }
    public string date { get; set; }
    public string categoryName { get; set; }
    public string sub_cat_name { get; set; }
    public string sub_sub_cat_name { get; set; }
    public string alias { get; set; }
    public string fullUrl { get; set; }
}

public class RootObject
{
    public int status { get; set; }
    public List<Story> response { get; set; }
}

Then, the code

    public MainPage() {
    InitializeComponent();
            onGetList();
    }
    protected async void onGetList() { 

        var content = await _client.GetStringAsync(url);
        var tr = JsonConvert.DeserializeObject<List<RootObject>>(content);
        ObservableCollection<RootObject> responses = new ObservableCollection<RootObject>(tr);

        //homePage.ItemsSource = responses
    }

I get an error on the statement

        var tr = JsonConvert.DeserializeObject<List<RootObject>>(content);

Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[App2.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) 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 'status', line 1, position 10.

What am I doing wrong, please?

Thanks in advance

Best wishes

Iyer

Best Answer

Answers

  • ColeXColeX Member, Xamarin Team Xamurai

    You got it wrong on the type of the json strings , it is Object not List.

    Change your code as

        var tr = JsonConvert.DeserializeObject<RootObject>(content);
        homePage.ItemsSource = tr.response ;
    
  • DirkWilhelmDirkWilhelm USMember ✭✭✭✭

    Your json only contains one "RootObject" but you are trying to deserialize it into a list.

    Try this: var tr = JsonConvert.DeserializeObject<RootObject>(content);

  • lillianlillian Member ✭✭

    @kyiyer You can have a try like this:
    var tr = JsonConvert.DeserializeObject<RootObject>(content);

  • kyiyerkyiyer Member ✭✭

    Hi everyone - many thanks for the responses. My code looks like this now

        protected async void onGetList() {
            var content = "[" + await _client.GetStringAsync(url) + "]";
            var tr = JsonConvert.DeserializeObject<RootObject>(content);
            homePage.ItemsSource = tr.Response;
        }
    

    And the XAML

        <ListView x:Name="homePage">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <StackLayout Orientation="Vertical">
                        <StackLayout Orientation="Horizontal">
                            <Label Text="{Binding title}">
    
                            </Label>
                            <Image Source="{Binding imageThumb}">
    
                            </Image>
                        </StackLayout>
                    </StackLayout>
                </DataTemplate>
            </ListView.ItemTemplate>
    
        </ListView>
    

    I still get the same error.

    You are all great for responding so fast. Many thanks

    Iyer

  • DirkWilhelmDirkWilhelm USMember ✭✭✭✭

    You shouldn't need the '[' and ']' around your content, remove them.

  • kyiyerkyiyer Member ✭✭

    Done - removed the brackets - but there is an invalid cast somewhere. Could it be the binding in the XAML? There are only two fields I am binding? Is the XAML binding syntax correct? Seems right to me?

    Unhandled Exception:

    System.InvalidCastException: Specified cast is not valid. occurred

  • ColeXColeX Member, Xamarin Team Xamurai

    Try to change the class name from Story to Response .

  • kyiyerkyiyer Member ✭✭

    I have removed the two bound fields in the XAML to see if the invalid cast gets fixed. But I still get the invalid cast error after removing the square brackets around the incoming XML.

  • kyiyerkyiyer Member ✭✭

    Tried changing class name from Story to Response - even though I did not understand why - same cast error

    Sigh - the joys of learning.

  • kyiyerkyiyer Member ✭✭
    Accepted Answer

    Fixed

    From here. Xamarin/XAML does not like a right after
    Need to put the in a - need to learn what is

    From this link
    https://stackoverflow.com/questions/40575870/xamarin-forms-binding-specified-cast-is-not-valid

    Thanks a lot

    Really appreciate it

    Iyer

Sign In or Register to comment.