Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# &引用;NullReferenceException";在Unity3D中尝试从JSON反序列化数据时_C#_Json_Parsing_Unity3d - Fatal编程技术网

C# &引用;NullReferenceException";在Unity3D中尝试从JSON反序列化数据时

C# &引用;NullReferenceException";在Unity3D中尝试从JSON反序列化数据时,c#,json,parsing,unity3d,C#,Json,Parsing,Unity3d,我需要从json文件中获取一些数据,我已经将其保存到名为dataAsJson的字符串中,在调试时,它如下所示: {\r\n\t\"question\":\r\n\t[\r\n\t\t{\r\n\t\t\"text\": \"głośniki\",\r\n\t\t\"correct\": \"speaker\",\r\n\t\t\"answer1\": \"speaker1\",\r\n\t\t\"answer2\": \"speaker2\",\r\n\t\t\"an

我需要从json文件中获取一些数据,我已经将其保存到名为dataAsJson的字符串中,在调试时,它如下所示:

    {\r\n\t\"question\":\r\n\t[\r\n\t\t{\r\n\t\t\"text\": 
    \"głośniki\",\r\n\t\t\"correct\": \"speaker\",\r\n\t\t\"answer1\": 
    \"speaker1\",\r\n\t\t\"answer2\": \"speaker2\",\r\n\t\t\"answer3\": 
    \"speaker3\"\r\n\t\t},\r\n\t\t{\r\n\t\t\"text\": 
    \"pustynia\",\r\n\t\t\"correct\": \"desert\",\r\n\t\t\"answer1\": 
    \"desert1\",\r\n\t\t\"answer2\": \"desert2\",\r\n\t\t\"answer3\": 
    \"deser3\"\r\n\t\t},\r\n\t\t{\r\n\t\t\"text\": 
    \"rycerz\",\r\n\t\t\"correct\": \"knight\",\r\n\t\t\"answer1\": 
    \"knight1\",\r\n\t\t\"answer2\": \"knight2\",\r\n\t\t\"answer3\": 
    \"knight3\"\r\n\t\t}\r\n\t]\r\n}
然后我使用JsonUtility.FromJson(dataAsjJson) 这是我的对象类:

    public class Question
    {
     public string text { get; set; }
     public string correct { get; set; }
     public string answer1 { get; set; }
     public string answer2 { get; set; }
     public string answer3 { get; set; }
    }
    public class RootObject
    {
        public List<Question> questions { get; set; }
    }

我需要成功地将其转换为C#object。

正如Amy在评论中提到的,您的C#类结构与您的JSON不匹配,我使用它是因为它准确快速。确保将[Serializable]放在每个类之上,这样我们就可以将数据结构或对象状态转换为Unity可以存储并在以后重新构建的格式。最后,在这个结构中我将避免使用getter和setter,这将导致序列化问题&unity建议使用字段

[Serializable]
public class Question
{
    public string text;
    public string correct;
    public string answer1;
    public string answer2;
    public string answer3;
}
[Serializable]
public class RootObject
{
    public List<Question> question;
}
[可序列化]
公开课问题
{
公共字符串文本;
公共字符串正确;
公共字符串应答器1;
公共字符串应答器2;
公共字符串应答器3;
}
[可序列化]
公共类根对象
{
公开名单问题;
}

您的c#模型与JSON不匹配。JSON是一个具有单个属性“question”的对象,其中包含一系列问题。您正试图将其反序列化为包含属性“questions”的对象,该属性包含一个问题数组。注意“s”。
可能会导致问题。。这会引起问题;)属性永远不会序列化,所以您应该始终使用字段进行序列化和反序列化。
[Serializable]
public class Question
{
    public string text;
    public string correct;
    public string answer1;
    public string answer2;
    public string answer3;
}
[Serializable]
public class RootObject
{
    public List<Question> question;
}