C# 使用JsonFX反序列化字典

C# 使用JsonFX反序列化字典,c#,json,serialization,unity3d,C#,Json,Serialization,Unity3d,我正在尝试序列化类型为dictionary的dictionary来存储一系列参数。字典包含基本变量类型和复杂变量类型(如列表)。序列化按预期工作,但是当将JSON字符串反序列化回字典时,属于列表类型的参数将转换为字典类型。当我尝试键入强制转换这些参数时,会得到一个InvalidCastException using UnityEngine; using System.Collections; using System.Collections.Generic; using JsonFx.Json;

我正在尝试序列化类型为
dictionary
的dictionary来存储一系列参数。字典包含基本变量类型和复杂变量类型(如列表)。序列化按预期工作,但是当将JSON字符串反序列化回
字典
时,属于
列表
类型的参数将转换为
字典
类型。当我尝试键入强制转换这些参数时,会得到一个
InvalidCastException

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using JsonFx.Json;

public class LevelBuilderStub : MonoBehaviour
{
    class Person
    {
        public string name;
        public string surname;
    }

    // Use this for initialization
    void Start ()
    {
        Dictionary<string, object> parameters = new Dictionary<string, object>();
        List<Person> persons = new List<Person>();
        persons.Add(new Person() { name = "Clayton", surname = "Curmi" });
        persons.Add(new Person() { name = "Karen", surname = "Attard" });

        parameters.Add("parameterOne", 3f);
        parameters.Add("parameterTwo", "Parameter string info");
        parameters.Add("parameterThree", persons.ToArray());

        string json = JsonWriter.Serialize(parameters);
        AVDebug.Log(json);

        parameters = null;
        parameters = JsonReader.Deserialize(json, typeof(Dictionary<string, object>)) as Dictionary<string, object>;

        foreach(KeyValuePair<string, object> kvp in parameters)
        {
            string key = kvp.Key;
            object val = kvp.Value;
            AVDebug.Log(string.Format("Key : {0}, Value : {1}, Type : {2}", key, val, val.GetType()));
        }
    }
}

问题是,如何获得参数键'parameterThree'的
列表
。请注意,参数字典的内容将根据其上下文而有所不同。

找到了解决方案!必须使用
JsonName
属性标记正在序列化的类,然后使用writer/reader设置将变量的程序集名称包含在JSON输出中。以前面的例子来说,这里是你必须做的

using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using JsonFx.Json;

[Serializable]
[JsonName("Person")]
public class Person
{
    public string name;
    public string surname;
}

[JsonName("Animal")]
public class Animal
{
    public string name;
    public string species;
}

[Serializable]
public class Parameters
{
    public float floatValue;
    public string stringValue;
    public List<Person> listValue;
}

public class SerializationTest : MonoBehaviour
{
    // Use this for initialization
    void Start()
    {
        ScenarioOne();
    }

    void ScenarioOne()
    {
        Dictionary<string, object> parameters = new Dictionary<string, object>();
        List<Person> persons = new List<Person>();
        persons.Add(new Person() { name = "Clayton", surname = "Curmi" });
        persons.Add(new Person() { name = "Karen", surname = "Attard" });

        List<Animal> animals = new List<Animal>();
        animals.Add(new Animal() { name = "Chimpanzee", species = "Pan troglodytes" });
        animals.Add(new Animal() { name = "Cat", species = "Felis catus" });

        parameters.Add("floatValue", 3f);
        parameters.Add("stringValue", "Parameter string info");
        parameters.Add("persons", persons.ToArray());
        parameters.Add("animals", animals.ToArray());

        // ---- SERIALIZATION ----

        JsonWriterSettings writerSettings = new JsonWriterSettings();
        writerSettings.TypeHintName = "__type";

        StringBuilder json = new StringBuilder();
        JsonWriter writer = new JsonWriter(json, writerSettings);
        writer.Write(parameters);

        AVDebug.Log(json.ToString());

        // ---- DESERIALIZATION ----

        JsonReaderSettings readerSettings = new JsonReaderSettings();
        readerSettings.TypeHintName = "__type";

        JsonReader reader = new JsonReader(json.ToString(), readerSettings);

        parameters = null;
        parameters = (Dictionary<string, object>)reader.Deserialize();

        foreach (KeyValuePair<string, object> kvp in parameters)
        {
            string key = kvp.Key;
            object val = kvp.Value;
            AVDebug.Log(val == null);
            AVDebug.Log(string.Format("Key : {0}, Value : {1}, Type : {2}", key, val, val.GetType()));
        }
    }
}
使用UnityEngine;
使用制度;
使用系统集合;
使用System.Collections.Generic;
使用系统文本;
使用JsonFx.Json;
[可序列化]
[JsonName(“人员”)]
公共阶层人士
{
公共字符串名称;
公共字符串姓氏;
}
[JsonName(“动物”)]
公营动物
{
公共字符串名称;
公共弦种;
}
[可序列化]
公共类参数
{
公众价值;
公共字符串字符串值;
公共列表列表值;
}
公共类序列化测试:MonoBehavior
{
//用于初始化
void Start()
{
场景一();
}
void scenarione()
{
字典参数=新字典();
列表人员=新列表();
添加(newperson(){name=“Clayton”,姓氏=“Curmi”});
添加(newperson(){name=“Karen”,姓氏=“Attard”});
列出动物=新列表();
添加(新动物(){name=“黑猩猩”,species=“Pan troglodytes”});
添加(新动物(){name=“Cat”,species=“Felis catus”});
参数。添加(“浮动值”,3f);
添加(“字符串值”、“参数字符串信息”);
parameters.Add(“persons”,persons.ToArray());
parameters.Add(“anists”,anists.ToArray());
//----序列化----
JsonWriterSettings writerSettings=新的JsonWriterSettings();
writerSettings.TypeHintName=“\uu类型”;
StringBuilder json=新的StringBuilder();
JsonWriter=newjsonwriter(json,writerSettings);
writer.Write(参数);
AVDebug.Log(json.ToString());
//----反序列化----
JsonReaderSettings readerSettings=新的JsonReaderSettings();
readerSettings.TypeHintName=“\uu类型”;
JsonReader=新的JsonReader(json.ToString(),readerSettings);
参数=null;
参数=(字典)reader.Deserialize();
foreach(参数中的KeyValuePair kvp)
{
字符串键=kvp.key;
对象值=kvp.Value;
AVDebug.Log(val==null);
Log(string.Format(“Key:{0},Value:{1},Type:{2}”,Key,val,val.GetType());
}
}
}

许多序列化库难以或无法处理多态性;特别是。
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using JsonFx.Json;

[Serializable]
[JsonName("Person")]
public class Person
{
    public string name;
    public string surname;
}

[JsonName("Animal")]
public class Animal
{
    public string name;
    public string species;
}

[Serializable]
public class Parameters
{
    public float floatValue;
    public string stringValue;
    public List<Person> listValue;
}

public class SerializationTest : MonoBehaviour
{
    // Use this for initialization
    void Start()
    {
        ScenarioOne();
    }

    void ScenarioOne()
    {
        Dictionary<string, object> parameters = new Dictionary<string, object>();
        List<Person> persons = new List<Person>();
        persons.Add(new Person() { name = "Clayton", surname = "Curmi" });
        persons.Add(new Person() { name = "Karen", surname = "Attard" });

        List<Animal> animals = new List<Animal>();
        animals.Add(new Animal() { name = "Chimpanzee", species = "Pan troglodytes" });
        animals.Add(new Animal() { name = "Cat", species = "Felis catus" });

        parameters.Add("floatValue", 3f);
        parameters.Add("stringValue", "Parameter string info");
        parameters.Add("persons", persons.ToArray());
        parameters.Add("animals", animals.ToArray());

        // ---- SERIALIZATION ----

        JsonWriterSettings writerSettings = new JsonWriterSettings();
        writerSettings.TypeHintName = "__type";

        StringBuilder json = new StringBuilder();
        JsonWriter writer = new JsonWriter(json, writerSettings);
        writer.Write(parameters);

        AVDebug.Log(json.ToString());

        // ---- DESERIALIZATION ----

        JsonReaderSettings readerSettings = new JsonReaderSettings();
        readerSettings.TypeHintName = "__type";

        JsonReader reader = new JsonReader(json.ToString(), readerSettings);

        parameters = null;
        parameters = (Dictionary<string, object>)reader.Deserialize();

        foreach (KeyValuePair<string, object> kvp in parameters)
        {
            string key = kvp.Key;
            object val = kvp.Value;
            AVDebug.Log(val == null);
            AVDebug.Log(string.Format("Key : {0}, Value : {1}, Type : {2}", key, val, val.GetType()));
        }
    }
}