我编写了两个测试,分别尝试对成功和失败的平面对象和嵌套对象进行反序列化,如下所示:
using NUnit.Framework;
using UnityEngine;
namespace Tests
{
public class FromJson
{
[Test]
public void Flat()
{
string json = "{\"data\":\"foo\"}";
Flat deserialized = JsonUtility.FromJson<Flat>(json);
Assert.AreEqual(deserialized.data, "foo");
var reserialized = JsonUtility.ToJson(deserialized);
Assert.AreEqual(json, reserialized);
}
[Test]
public void Nested()
{
string json = "{\"data\":{\"data\":\"foo\"}}";
Nested deserialized = JsonUtility.FromJson<Nested>(json);
Assert.AreEqual(deserialized.data.data, "foo");
var reserialized = JsonUtility.ToJson(deserialized);
Assert.AreEqual(json, reserialized);
}
}
}
public class Flat
{
public string data;
}
public class Nested
{
public Data data;
}
public class Data
{
public string data;
}
失败的输出如下所示:
Nested (0.009s)
---
System.NullReferenceException : Object reference not set to an instance of an object
---
at Tests.FromJson.Nested () [0x0000e] in /Users/bgates/Unity/Virtual Store/Assets/Tests/Serialization.cs:23
at (wrapper managed-to-native) System.Reflection.MonoMethod.InternalInvoke(System.Reflection.MonoMethod,object,object[],System.Exception&)
at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00032] in <ac823e2bb42b41bda67924a45a0173c3>:0
任何帮助将不胜感激。谢谢!
答案 0 :(得分:1)
事实证明我想念[System.Serializable]
。
以下测试通过:
using NUnit.Framework;
using UnityEngine;
namespace Tests
{
public class FromJson
{
[Test]
public void Flat()
{
string json = "{\"foo\":\"bar\"}";
Flat deserialized = JsonUtility.FromJson<Flat>(json);
Assert.AreEqual(deserialized.foo, "bar");
var reserialized = JsonUtility.ToJson(deserialized);
Assert.AreEqual(json, reserialized);
}
[Test]
public void Nested()
{
string json = "{\"foo\":{\"foo\":\"bar\"}}";
Nested deserialized = JsonUtility.FromJson<Nested>(json);
Assert.AreEqual(deserialized.foo.foo, "bar");
var reserialized = JsonUtility.ToJson(deserialized);
Assert.AreEqual(json, reserialized);
}
}
}
[System.Serializable]
class Foo
{
public string bar;
}
[System.Serializable]
public class Flat
{
public string foo;
}
[System.Serializable]
public class Nested
{
public Foo2 foo;
}
[System.Serializable]
public class Foo2
{
public string foo;
}