繁体   English   中英

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

[英]Deserializing and Serializing JSON File in C#

我正在尝试将一个object(Item)序列化为一个文件,该文件每次调用该函数时都会附加更多的Item对象。

它一直给我这个错误:

07-12 15:43:27.931 I / MonoDroid(17468):Newtonsoft.Json.JsonSerializationException:无法将当前JSON对象(例如{“ name”:“ value”})反序列化为类型'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.");
            }
        }
    }
}

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

您不能仅将两个序列化的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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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