【问题标题】:Deserializing and Serializing JSON File in C#在 C# 中反序列化和序列化 JSON 文件
【发布时间】:2016-11-14 21:30:00
【问题描述】:

我正在尝试将一个对象(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.");
            }
        }
    }
}

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

【问题讨论】:

  • 异常信息告诉你出了什么问题。你得到一个项目,但你想把它作为一个项目列表来获取。将您的 DeserializeObject>() 更改为 DeserializeObject() 它应该运行。
  • 你不能只是将两个序列化的 json 对象附加在一起。您需要将它们解析为单个 json 数组,然后将它们序列化在一起。
  • @tequilaslammer 不允许我遍历 itemList
  • @Jason 我该怎么做?这就是我不明白的

标签: c# android json serialization xamarin


【解决方案1】:

你不能只是将两个序列化的 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);

【讨论】:

  • 这对我来说你刚刚写的东西没有意义。它看起来和我写的很相似。你能在我的代码的正确位置用你的代码重写你的答案吗,因为我不明白你写了什么。 ☺
  • 您的代码序列化一个 SINGLE 对象,然后将其附加到现有文件中。我将对象添加到列表中,序列化整个列表,然后写入(而不是附加)它
  • 在哪里?我不是读心术 - 如果你需要帮助,你需要告诉我是哪一行导致了异常。
  • “Serialize”是指将Object转为json或其他可写格式。
  • 我在示例中有错字 - 请参阅更正(倒数第二行)
猜你喜欢
  • 2017-05-16
  • 2014-01-06
  • 1970-01-01
  • 1970-01-01
  • 2020-10-23
  • 1970-01-01
  • 1970-01-01
  • 2021-01-11
  • 2021-01-13
相关资源
最近更新 更多