【发布时间】:2014-02-01 07:00:45
【问题描述】:
我正在尝试序列化Dictionary<string, object> 类型的字典以存储一系列参数。字典包含原始变量类型和复杂变量类型(例如列表)。序列化按预期工作,但是当将 JSON 字符串反序列化回Dictionary<string, object> 时,List<T> 类型的那些参数将转换为Dictionary<string, object> 类型。当我尝试输入这些参数时,我得到一个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()));
}
}
}
这将返回以下内容;
{"parameterOne":3,"parameterTwo":"Parameter string info","parameterThree":[{"name":"Clayton","surname":"Curmi"},{"name":"Karen","surname":"Attard"}]}
Key : parameterOne, Value : 3, Type : System.Int32
Key : parameterTwo, Value : Parameter string info, Type : System.String
Key : parameterThree, Value : System.Collections.Generic.Dictionary`2[System.String,System.Object][], Type : System.Collections.Generic.Dictionary`2[System.String,System.Object][]
问题是,我怎样才能获得参数键“parameterThree”的List<Person>。请注意,参数字典的内容会根据其上下文而有所不同。
【问题讨论】:
标签: c# json serialization unity3d