在C#中反序列化和序列化JSON文件

时间:2016-07-12 14:51:39

标签: c# android json serialization xamarin

我尝试将对象(Item)序列化为每次调用函数时附加了更多Item对象的文件。

它一直给我这个错误:

  

07-12 15:43:27.931 I / MonoDroid(17468):Newtonsoft.Json.JsonSerializationException:无法反序列化当前的JSON对象(例如{" name":" value" })in type' System.Collections.Generic.List`1 [WaterApp.Item]'因为该类型需要JSON数组(例如[1,2,3])才能正确反序列化。   07-12 15:43:27.931 I / MonoDroid(17468):要修复此错误,请将JSON更改为JSON数组(例如[1,2,3])或更改反序列化类型以使其成为正常的.NET类型(例如,不是像整数这样的基本类型,不是像数组或列表那样的集合类型),可以从JSON对象反序列化。 JsonObjectAttribute也可以添加到类型中以强制它从JSON对象反序列化。

这是对象类:

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;
        }
    }
}

以下是使用方法完成数据处理的类:

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.");
            }
        }
    }
}

有人可以向我推进正确的方向或以任何方式帮助解决此错误吗?我不太确定如何解决错误问题。我不明白错误要求的代码。

1 个答案:

答案 0 :(得分:2)

你不能只将两个序列化的json对象附加在一起 ​​- 这不会产生有效的json。相反,您需要读入现有列表,将项目添加到其中,然后再将其序列化

// 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);