【发布时间】: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