0

Hello I have a big JSON file representing countries and their total cases and deaths from covid. All I want to do is to display the data of the JSON in to my AboutPage. I have tried various ways, but no-one is working for me. Any idea how I should work?

I am giving you a small part of the JSON

[{
  "regionData": [
    {
      "country": "World",
      "totalCases": 157341642,
      "newCases": 651328,
      "totalDeaths": 3278509,
      "newDeaths": 9126,
      "totalRecovered": 135480211,
      "activeCases": 18582922,
      "seriousCritical": 108879,
      "casesPerMil": 20185,
      "deathsPerMil": 420.6,
      "totalTests": 0,
      "testsPerMil": 0,
      "population": 0
    },
    {
      "country": "India",
      "totalCases": 21886556,
      "newCases": 401271,
      "totalDeaths": 238265,
      "newDeaths": 4194,
      "totalRecovered": 17917013,
      "activeCases": 3731278,
      "seriousCritical": 8944,
      "casesPerMil": 15729,
      "deathsPerMil": 171,
      "totalTests": 298601699,
      "testsPerMil": 214596,
      "population": 1391457000
    },  ]
}]

var assembly = typeof(AboutPage).GetTypeInfo().Assembly; Stream stream = assembly.GetManifestResourceStream("MaybeThisOne.testmodel.json");

        using (var reader = new System.IO.StreamReader(stream))
        {
            var json = reader.ReadToEnd();

            List<TestModel> mylist = JsonConvert.DeserializeObject<List<TestModel>>(json);
            myrootobject = new ObservableCollection<TestModel>(mylist);
            MyListView.ItemsSource = myrootobject;

JsonConvert.DeserializeObject<List> In this part i have error saying cannot be used like method. I tried to remove the parenthesis but nothing happened

UPDATED:

I did the steps that were suggested, 1. create a C# model using json2csharp.com, 2. deserialize using newtonsoft. The build is happening and the app starts, but when I try to enter the created page, it terminates the app without any error message.

UPDATED 2:

I started a new project and followed the above steps. The only error I get is about Page3. I have to call it in the shell from jsonarray folder. How should I do it?

e.x <ShellContent Title="About" Icon="icon_about.png" Route="AboutPage" ContentTemplate="{DataTemplate local:AboutPage}" />

Please can you tell me how should I call Page3 from jsonarray folder? Thanks in advance!!!

UPDATE 3

I have started the project from scratch and it partially worked. The only problem is that it doesn't show all the binding fields.

Any idea?

enter image description here

  • 1. create a C# model using json2csharp.com, 2. deserialize using newtonsoft, 3. display using a CollectionView or other UI – Jason May 10 '21 at 15:43
  • https://stackoverflow.com/questions/44778592/how-to-display-json-data-in-xamarin-forms-list-view – Jason May 10 '21 at 15:44
  • Yes I did all of the above. – Nikolaos Efentis May 10 '21 at 15:54
  • please do not stuff code in the comments, [edit] your question and format it properly so it's readable. And if you did this and it did not work, you need to **describe the problem**. Just saying "no-one is working for me" is not a helpful description of the problem you are having. Do you get errors or exceptions? Have you attempted to debug the code to determine where the problem is? Please read [ask] for guidance in writing an on-topic question. – Jason May 10 '21 at 15:56
  • sorry for this, I posted in the original question the code I used to deserialize. – Nikolaos Efentis May 10 '21 at 15:59
  • please post the **exact error message** – Jason May 10 '21 at 16:00
  • Non-invocable member '.DeserializeObject' cannot be used like a method. – Nikolaos Efentis May 10 '21 at 16:03
  • are you sure that `json` is not null and contains a valid json string? – Jason May 10 '21 at 16:05
  • I am pretty sure, where can I check it to be 100% sure? in .json file? Sorry for bad questions, I am very new to xamarin :) – Nikolaos Efentis May 10 '21 at 16:12
  • use the debugger, or if you don't know how write it to the console – Jason May 10 '21 at 16:14

1 Answers1

1

I use Newtonsoft.Json 13.0.1 to convert JSON Array Objects into generic list, and I also modify your json.json file, remove the outer brackets. setting json.json file Build Action as Embedded resource

{
"regionData": [
  {
    "country": "World",
    "totalCases": 157341642,
    "newCases": 651328,
    "totalDeaths": 3278509,
    "newDeaths": 9126,
    "totalRecovered": 135480211,
    "activeCases": 18582922,
    "seriousCritical": 108879,
    "casesPerMil": 20185,
    "deathsPerMil": 420.6,
    "totalTests": 0,
    "testsPerMil": 0,
    "population": 0
  },
  {
    "country": "India",
    "totalCases": 21886556,
    "newCases": 401271,
    "totalDeaths": 238265,
    "newDeaths": 4194,
    "totalRecovered": 17917013,
    "activeCases": 3731278,
    "seriousCritical": 8944,
    "casesPerMil": 15729,
    "deathsPerMil": 171,
    "totalTests": 298601699,
    "testsPerMil": 214596,
    "population": 1391457000
  }
]
}

There is regionData property containing list data, so you need to create new class TestList, contains List regionData property

 public class TestList
{
    public List<TestModel> regionData { get; set; }
}

public class TestModel
{       
    public string country { get; set; }
    public string totalCases { get; set; }
}

ContentPage.cs:

  public Page3()
    {
        InitializeComponent();
        TestList modellist = new TestList();
      

        var assembly = typeof(jsonarray.Page3).GetTypeInfo().Assembly;          
        Stream stream = assembly.GetManifestResourceStream("FormsSample.json3.json");
        using (var reader = new System.IO.StreamReader(stream))
        {
            var jsonString = reader.ReadToEnd();

            //Converting JSON Array Objects into generic list               
            modellist = JsonConvert.DeserializeObject<TestList>(jsonString);

            
            listview1.ItemsSource = modellist.regionData;
        }
    }

Finally, I have the list data in ListView, having no problem.

Update:

My project name is FormsSample, and I add Json3.json file in root directory, Build Action as Embedded resource, you can see the following screenshot.

Page 3 is one ContentPage, contains ListView, to display Json data.

<ContentPage
x:Class="FormsSample.jsonarray.Page3"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
<ContentPage.Content>
    <StackLayout>
        <ListView x:Name="listview1">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Orientation="Horizontal">
                            <Label Text="{Binding country}" />
                            <Label
                                HorizontalOptions="CenterAndExpand"
                                Text="{Binding totalCases}"
                                VerticalOptions="CenterAndExpand" />
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>
</ContentPage.Content>

enter image description here

Cherry Bu - MSFT
  • 10,160
  • 1
  • 10
  • 16
  • Hello @Cherry BU . I am a bit confused using Page3(), as also "FormsSample.json3.json". Can you explain to me how should I continue? I have create a class TestList as you told me – Nikolaos Efentis May 11 '21 at 14:07
  • @NikolaosEfentis My project name is FormsSample, and I add Json3.json file in root directory, Build Action as Embedded resource. Page 3 is one ContentPage, contains ListView, to display Json data. Please see my update. – Cherry Bu - MSFT May 12 '21 at 01:55
  • can you tell me how to call page3 from jsonarray folder, in AppShell.xaml? – Nikolaos Efentis May 13 '21 at 18:01
  • Cherry I created a new page in root but it doesn't work, see updated above – Nikolaos Efentis May 13 '21 at 18:31
  • @NikolaosEfentis You use Xamarin.shell? Can you upload your sample at github or onedrive, I will download your sample to test, to see what problem you encounter. – Cherry Bu - MSFT May 14 '21 at 01:22
  • Is there a way to send you the project privately? It is for dissertation and ii has plagiarism check, I would like to avoid sharing the code with everyone until the assignment is uploaded – Nikolaos Efentis May 14 '21 at 12:03
  • @NikolaosEfentis Send your project public, it is beneficial to resolve your problem through everyone. – Cherry Bu - MSFT May 17 '21 at 08:27