使用JsonFX反序列化字典 [英] Deserialize a dictionary with JsonFX

查看:218
本文介绍了使用JsonFX反序列化字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试序列化Dictionary<string, object>类型的字典以存储一系列参数.字典包含原始变量类型和复杂变量类型(例如列表).序列化按预期工作,但是将JSON字符串反序列化为Dictionary<string, object>时,那些类型为List<T>的参数将转换为类型为Dictionary<string, object>.当我尝试对这些参数进行类型转换时,得到一个InvalidCastException.

I'm trying to serialize a dictionary of type Dictionary<string, object> to store a series of parameters. The dictionary contains both primitive and complex variable types (such lists). Serialization works as expected however when deserializing the JSON string back to a Dictionary<string, object>, those parameters that are of type List<T> are transformed to a type Dictionary<string, object>. When I try to type cast these parameters, I get an 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>.请注意,参数字典的内容将根据其上下文而有所不同.

The question is, how can I get a List<Person> for parameter key 'parameterThree'. Please note that the contents of the parameters dictionary will be different depending on its context.

推荐答案

找到了解决方案!必须使用JsonName属性标记要序列化的类,然后使用writer/reader设置将变量的程序集名称包含在JSON输出中.以前面的示例为例,这是您要做的;

Found the solution! One has to tag the class being serialised using the JsonName attribute and then use writer/reader settings to include the assembly name of the variable in the JSON output. Taking the previous example, here is what you have to do;

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()));
        }
    }
}

这篇关于使用JsonFX反序列化字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆