简体   繁体   中英

How to convert JSON to custom object class in C# and access properties

I am very new to c# and I am trying to manipulate data from the api restcountries.eu. I am having issues determining where exactly to place the code to convert the data. My desired outcome is to display the currency name of a specific country (identified by the 3-digit alpha code) through the console.

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

namespace ApiPractice
{
    public class Country
    {
        //Alpha3code
        public string Alpha3Code { get; set; }
        //country name
        public string Name { get; set; }
        //population
        public int Population { get; set; }
        //public string Languages { get; set; }
        //flag
        public string Flag { get; set; }
        //timezone
        public string[] TimeZones { get; set; }
        //capital
        public string Capital { get; set; }
        //currency
        public Currency Currencies { get; set; }
        ////bordering countries
        public string[] Borders { get; set; }
    }

    public partial class Currency
    {
        [JsonProperty("code")]
        public string Code { get; set; }
        [JsonProperty("Name")]
        public string Name { get; set; }
        [JsonProperty("Symbol")]
        public string Symbol { get; set; }
    }
    class Program
    {
        readonly static HttpClient client = new HttpClient();

        static void ShowProduct(Country country)
        {
            Console.WriteLine(country.Currencies.Name);

        }
        static string ConvertStringArrayToString(string[] array)
        {
            // Concatenate all the elements into a StringBuilder.
            StringBuilder builder = new StringBuilder();
            foreach (string value in array)
            {
                builder.Append(value);
                builder.Append(',');
            }
            return builder.ToString();
        }


            static async Task<Country> GetCountryAsync(string path)
        {
            Country country = null;
            HttpResponseMessage response = await client.GetAsync(path);
            if (response.IsSuccessStatusCode)
            {
                country = await response.Content.ReadAsAsync<Country>();

            }
            return country;
        }



        static void Main()
        {
            RunAsync().GetAwaiter().GetResult();
        }

        static async Task RunAsync()
        {
            // Update port # in the following line.
            client.BaseAddress = new Uri("https://restcountries.eu/rest/v2/alpha/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

            try
            {
                Console.WriteLine("Please write the alpha numeric code for the country requested");

                var alphacode= Console.ReadLine();


                // Get the product
                var product = await GetCountryAsync(alphacode);
                ShowProduct(product);



            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.ReadLine();
        }
}



}

Currently this is the error message I am getting in the console:

Please write the alpha numeric code for the country requested

usa

Cannot deserialize the current JSON array (eg [1,2,3]) into type 'ApiPractice.Currency' because the type requires a JSON object (eg {"name":"value"}) to deserialize correctly.

To fix this error either change the JSON to a JSON object (eg {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (eg ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.

Path 'currencies', line 1, position 581.

JSON:

{
    "name": "United States of America",
    "topLevelDomain": [
        ".us"
    ],
    "alpha2Code": "US",
    "alpha3Code": "USA",
    "callingCodes": [
        "1"
    ],
    "capital": "Washington, D.C.",
    "altSpellings": [
        "US",
        "USA",
        "United States of America"
    ],
    "region": "Americas",
    "subregion": "Northern America",
    "population": 323947000,
    "latlng": [
        38.0,
        -97.0
    ],
    "demonym": "American",
    "area": 9629091.0,
    "gini": 48.0,
    "timezones": [
        "UTC-12:00",
        "UTC-11:00",
        "UTC-10:00",
        "UTC-09:00",
        "UTC-08:00",
        "UTC-07:00",
        "UTC-06:00",
        "UTC-05:00",
        "UTC-04:00",
        "UTC+10:00",
        "UTC+12:00"
    ],
    "borders": [
        "CAN",
        "MEX"
    ],
    "nativeName": "United States",
    "numericCode": "840",
    "currencies": [
        {
            "code": "USD",
            "name": "United States dollar",
            "symbol": "$"
        }
    ],
    "languages": [
        {
            "iso639_1": "en",
            "iso639_2": "eng",
            "name": "English",
            "nativeName": "English"
        }
    ],
    "translations": {
        "de": "Vereinigte Staaten von Amerika",
        "es": "Estados Unidos",
        "fr": "États-Unis",
        "ja": "アメリカ合衆国",
        "it": "Stati Uniti D'America",
        "br": "Estados Unidos",
        "pt": "Estados Unidos",
        "nl": "Verenigde Staten",
        "hr": "Sjedinjene Američke Države",
        "fa": "ایالات متحده آمریکا"
    },
    "flag": "https://restcountries.eu/data/usa.svg",
    "regionalBlocs": [
        {
            "acronym": "NAFTA",
            "name": "North American Free Trade Agreement",
            "otherAcronyms": [],
            "otherNames": [
                "Tratado de Libre Comercio de América del Norte",
                "Accord de Libre-échange Nord-Américain"
            ]
        }
    ],
    "cioc": "USA"
}

Cannot deserialize the current JSON array (eg [1,2,3]) into type 'ApiPractice.Currency' because the type requires a JSON object (eg {"name":"value"}) to deserialize correctly. To fix this error either change the JSON to a JSON object (eg {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (eg ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array. Path 'currencies', line 1, position 581.

The error means that the property "currencies" of your JSON is an array, but in your class Country, the type of the property Currencies is the object Currency. You must change the type of the property Currencies from Currency to a list of Currency.

The code of your property should be:

public IList<Currency> Currencies { get; set; }

Moreover, it is a good practice to initialize lists in the constructor of the class. So, in the class Country, you must implement the following constructor:

public Country() {
    Currencies = new List<Currency>();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM