Imdad
Imdad

Reputation: 769

Deserializing and Serializing JSON File in C#

I'm trying to serialize an object(Item) to a file that gets appended with more Item objects each time the function is called.

It keeps giving me this error:

07-12 15:43:27.931 I/MonoDroid(17468): Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[WaterApp.Item]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. 07-12 15:43:27.931 I/MonoDroid(17468): 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.

Here is the object class:

using System;
using System.Collections;
using Android.Content;
using Android.Preferences;
using Java.IO;

namespace WaterApp
{
    public class Item
    {
        public bool Type { get; set; }
        public string ItemName { get; set; }
        public DateTime ExpiryDate { get; set; }
        public int ItemIconNumber { get; set; }

        public Item(bool type, string itemName, DateTime expiryDate, int itemIconNumber)
        {
            Type = type;
            ItemName = itemName;
            ExpiryDate = expiryDate;
            ItemIconNumber = itemIconNumber;
        }
    }
}

Here is the class where the data handling is done with methods:

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using Console = System.Console;
using Environment = System.Environment;
using File = System.IO.File;
using JsonWriter = Newtonsoft.Json.JsonWriter;

namespace WaterApp.Droid
{
    public abstract class DataHandler
    {

        private static string documentsPath = System.Environment.GetFolderPath(Environment.SpecialFolder.Personal);
        private static string filePath = Path.Combine(documentsPath, "HatchListData.json");

        public static void SaveObjectToFile(Item item)
    {
        // read in the existing list
        // IMPORTANT - if this is the first time and the file doesn't exist, then
        // you need to initialise itemList = new List<Item>();
        var itemList = new List<Item>();
        File.WriteAllText(filePath, String.Empty);
        string json = File.ReadAllText(filePath);
        itemList = JsonConvert.DeserializeObject<List<Item>>(json);

        // add a new item
        itemList.Add(item);

        // serialize the list and write it out again
        json = JsonConvert.SerializeObject(itemList, Formatting.Indented);
        File.WriteAllText(filePath, json);
        Console.WriteLine(File.ReadAllText(filePath));
    }

        public static void LoadList(List<Item> listToBeLoaded)
        {
            string json = "";

            if (File.Exists(filePath))
            {
                if (filePath.Length > 2)
            {
                Console.WriteLine("READING" + "READ!");

                using (StreamReader streamReader = new StreamReader(filePath))
                {
                    string json = streamReader.ReadToEnd();
                    listToBeLoaded = JsonConvert.DeserializeObject<List<Item>>(json);
                }

                Console.WriteLine("READING" + "loaded");
            }
            }
            else
            {
                Console.WriteLine("READING" + "Doesn't exist, json file.");
            }
        }
    }
}

Please can someone push me in the right direction or help fix this error in any way? I'm not too sure how to fix the issue of the error. I don't understand what code the error is asking for.

Upvotes: 0

Views: 2358

Answers (1)

Jason
Jason

Reputation: 89102

you can't just append two serialized json objects together - that won't produce valid json. Instead, you need to read in the existing list, add the items to it, and then serialize it out again

// read in the existing list
// IMPORTANT - if this is the first time and the file doesn't exist, then
// you need to initialise itemList = new List<Item>();
json = File.ReadAllText(filePath);
var itemList = JsonConvert.DeserializeObject<List<Item>>(json);

// add a new item
itemList.Add(newItem);

// serialize the list and write it out again
string json = JsonConvert.SerializeObject(itemList, Formatting.Indented);
File.WriteAllText(path,json);

Upvotes: 2

Related Questions