【问题标题】:Can JsonUtility.FromJson deserialize nested values?JsonUtility.FromJson 可以反序列化嵌套值吗?
【发布时间】:2019-03-11 00:58:23
【问题描述】:

我正在尝试反序列化具有深度嵌套值的 JSON 对象,但所有尝试都为空。下面是一个失败的测试,但我希望它通过。有人可以解释我缺少什么吗?

using System.Collections.Generic;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools;

[System.Serializable]
class TestJson
{
  public string rootStr;
  public Foo foo;
}

[System.Serializable]
class Foo
{
  public string bar;
}

namespace Tests
{
  public class Serialization
  {
    [Test]
    public void SerializationSimplePasses()
    {
      string json = "{\"foo\":{\"bar\":\"baz\"},\"rootStr\":\"rootStrValue\"}";
      var deserialized = JsonUtility.FromJson<TestJson>(json);
      Assert.AreEqual(deserialized.rootStr, "rootStrValue"); // this works
      Assert.AreEqual(deserialized.foo.bar, "baz"); // this fails
      var reserialized = JsonUtility.ToJson(deserialized);
      Assert.AreEqual(reserialized, json); // this fails
    }

  }
}

【问题讨论】:

    标签: c# json unity3d


    【解决方案1】:

    第一个断言

    Assert.AreEqual(deserialized.foo.bar, "baz");
    

    实际上对我有用。


    从您班级中字段的顺序来看,我希望reserialized 具有价值

    "{\"rootStr\":\"rootStrValue\", \"foo\":{\"bar\":\"baz\"}}";
    

    因为它是从上到下的。这显然不完全等于给定字符串json,尽管它具有基本相同的内容。

    所以

    Assert.AreEqual(reserialized, json); 
    

    只要您的原始输入 json 没有与

    完全匹配的顺序,就会始终失败
    JsonUtility.ToJson(deserialized);
    

    顺便说一句,这也正是输出已经告诉你的内容:

    SerializationSimplePasses (0,027s)
    ---
    字符串长度均为 46。字符串在索引 2 处不同。
    预期:"{"rootStr":"rootStrValue","foo":{"bar":"baz"}}"
    但是是:"{"foo":{"bar":"baz"},"rootStr":"rootStrValue"}"
    -------------^
    ---
    在 E:...\Assets\Tests\NewTestScript.cs:31

    中的 Tests.Serialization.SerializationSimplePasses () [0x0003c]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-21
      • 1970-01-01
      相关资源
      最近更新 更多