Home > Net >  How to put the object I get from input in an JSON array?
How to put the object I get from input in an JSON array?

Time:11-04

I'm doing a weather forecasting console app. I ask the user if they want to save the input location. When they enter longitude and latitude, it is saved in JSON file, so later on(on the second try) they can just select the city from the list. The problem is that when the city object is saved in a JSON file, it is not in an array, which is why later on I don't get the list displayed.

Program.cs

//saving city objcet in JSON file
            if (userLoc == 1)
            {
                IConfiguration citConfiguration = new Configuration("cities.json");
                var CitiesConfig = new City()
                {
                    Id = 1,
                    CityName = $"{weatherInfo.Timezone}",
                    Lng = weatherInfo.Longitude,
                    Lat = weatherInfo.Latitude
                };
                citConfiguration.SetConfigs(CitiesConfig);
            }

City.cs

using Weather.PCL.Models.Abstractions;
using Configs.Models.Abstractions;

namespace Weather.PCL.Models.Implementations
{
    public class City : ICity, IConfig
    {
        public int Id { get; set; }
        public string CityName { get; set; }
        public double Lng { get; set; }
        public double Lat { get; set; }
    }
}

setting config

public bool SetConfigs(IConfig config)
    {
        try
        {
            using (StreamWriter sw = new StreamWriter(_path))
            {
                var json = JsonConvert.SerializeObject(config);
                sw.Write(json);

                sw.Close();
                return true;
            }
        }
        catch (Exception ex)
        {
            return false;
        }
    }

displaying the list of cities in JSON file

var citiesJson = configuration.GetConfigs();
                var citiesArray = JsonConvert.DeserializeObject<City[]>(citiesJson);

                foreach (var item in citiesArray)
                {
                    Console.WriteLine(item.Id   ". "   item.CityName);
                }

When I run the project I get an exception Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'Weather.PCL.Models.Implementations.City[]'

What can I do?

CodePudding user response:

Your JSON string do not contain JSON array . Make sure your JSON string look like this: [{"aaa":"a1","bbb":"b1","ccc":null},{"aaa":"a2","bbb":"b2","ccc":null}]

CodePudding user response:

Instead of one city you have to create array of cities

 var CitiesConfig = new City[] {  
        new City
                {
                    Id = 1,
                    CityName = $"{weatherInfo.Timezone}",
                    Lng = weatherInfo.Longitude,
                    Lat = weatherInfo.Latitude
                }
               };

to write

public bool SetConfigs(City[] config)
    {
        try
        {
            using (StreamWriter sw = new StreamWriter(@"cities.json"))
            {
                var json = JsonConvert.SerializeObject(config);
                sw.Write(json);

                sw.Close();
                return true;
            }
        }
        catch (Exception ex)
        {
            return false;
        }
    }

and to test

string json = string.Empty;
    using (StreamReader r = new StreamReader(@"cities.json"))
        json = r.ReadToEnd();
        
    var citiesArray = JsonConvert.DeserializeObject<City[]>(json);

    foreach (var item in citiesArray)
    {
        Console.WriteLine(item.Id   ". "   item.CityName);
    }
  • Related