我只想序列化一些数据并反序列化它,它必须在iOS平台上工作。Json.NET不适用于iOS。JsonFX可以序列化数据,并且字符串看起来像由Json.Net序列化的字符串,但是JsonFX不能反序列化数据。下面是简单的代码,给出了下一个错误
InvalidCastException:不能从源类型转换到目标类型。
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
using Pathfinding.Serialization.JsonFx;
public class jsonTest : MonoBehaviour {
public Text text;
public List<ChapterModel> chapters;
// Use this for initialization
void Start () {
chapters = new List<ChapterModel>();
for(int i=0; i<2; i++)
{
var cm = new ChapterModel();
cm.pages = new List<PageModel>();
cm.id = i;
for(int j =0; j<2; j++)
{
var pm = new PageModel();
pm.BackgroundArt = j.ToString();
cm.pages.Add(pm);
}
chapters.Add(cm);
}
Debug.Log(JsonReader.Deserialize<List<ChapterModel>>(JsonWriter.Serialize(chapters)).Count);
}
}有人知道怎么修吗?
发布于 2015-11-29 02:23:37
在与JsonFX玩了一会儿之后,我发现它的使用非常棘手:
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
using System.Linq;
using Pathfinding.Serialization.JsonFx;
using UnityEditor;
public class jsonTest : MonoBehaviour
{
public Text text;
public List<ChapterModel> chapters;
// Use this for initialization
void Start()
{
chapters = new List<ChapterModel>();
for (int i = 0; i < 2; i++)
{
var cm = new ChapterModel();
cm.pages = new List<PageModel>();
cm.id = i;
for (int j = 0; j < 2; j++)
{
var pm = new PageModel();
pm.BackgroundArt = j.ToString();
cm.pages.Add(pm);
}
chapters.Add(cm);
}
string json = JsonWriter.Serialize(chapters);
//Will end up in in invalid cast:
//var deserialized = JsonReader.Deserialize<List<ChapterModel>(json);
//Will be casted to object[] on deserialization:
//var deserialized = JsonReader.Deserialize(json, typeof (List<ChapterModel>));
//Will evaluate just fine:
var deserialized = JsonReader.Deserialize(json, typeof(List<ChapterModel>)) as object[];
List<ChapterModel> list = deserialized.Select(item => item as ChapterModel).ToList();
Debug.Log(list.Count);
}
}
[System.Serializable]
public class ChapterModel
{
public int id = -1;
public List<PageModel> pages;
}
[System.Serializable]
public class PageModel
{
public string BackgroundArt,
ForeAddedArt,
VFXloop, VFXappeared, VFXnextSlide,
BGAmbientLoop, BGMusicLoop, BGVoiceLoop,
VFXSound, MusicSound, VoiceSound;
}但是,如果我们让我们的JSON知道一个typehint,它应该是好的。有趣的是,这不是:
//(...)
StringBuilder output = new StringBuilder();
JsonWriterSettings writerSettings = new JsonWriterSettings { TypeHintName = "__type" };
JsonWriter writer = new JsonWriter(output, writerSettings);
writer.Write(chapters);
JsonReaderSettings readerSettings = new JsonReaderSettings { TypeHintName = "__type" };
JsonReader reader = new JsonReader(output, readerSettings);
//Will now see objects inside array as ChapterModel but still will fail to cast properly to list/array of ChapterModels
List<ChapterModel> deserialized = reader.Deserialize() as List<ChapterModel>;
Debug.Log(deserialized.Count);你可能想多玩一点,或者坚持我上面提供的丑陋版本。
https://stackoverflow.com/questions/33973892
复制相似问题