C#.Net反序列化$类型不起作用

时间:2016-09-22 15:15:50

标签: c# .net json serialization unity3d

我正在尝试使用$ type属性反序列化json。但是,我收到一条错误,指出“JSON中指定的类型未解决。我不确定我做错了什么。非常感谢任何帮助。

我的JSON

{
movies:
[
    {
        $type:"RTMoviePageWithSlides",
        title:"Reservoir Dogs",
        slides:[
            {$type:"RTCharacterPage", title:"Mr. Orange",       img:""},
            {$type:"RTCharacterPage", title:"Mr. Blonde",       img:""},
            {$type:"RTCharacterPage", title:"Mr. White",        img:""},
            {$type:"RTCharacterPage", title:"Mr. Pink",         img:""},
            {$type:"RTCharacterPage", title:"Nice Guy Eddie",   img:""},
        ]
    }
    {
        $type:"RTMoviePageWithSubpages",
        title:"Jackie Brown",
        pages:[
            {$type:"RTActorPage", title:"Pam Gier",             other_movies:[]},
            {$type:"RTActorPage", title:"Samuel L. Jackson",    other_movies:[]},
            {$type:"RTActorPage", title:"Robert Forester",      other_movies:[]}
        ]
    }
]
}

我的课程

using System.Collections;
using System.Collections.Generic;

public class RTMovieData {
    public List<RTMoviePage> movies;    
}

public class RTMoviePage {
    public string title;
}

public class RTMoviePageWithSlides : RTMoviePage{
    public List<RTMoviePage> slides = new List<RTSlidePageData>{};
}

public class RTMoviePageWithSubpages : RTMoviePage{
    public List<RTMoviePage> pages = new List<RTPageData>{};
}

public class RTCharacterPage : RTMoviePage
{
    public string img;
}

public class RTActorPage : RTMoviePage
{
    public  List<string>other_movies;
}

反序列化代码

var settings = new JsonSerializerSettings();
    settings.TypeNameHandling = TypeNameHandling.Auto;

    RTMovieData data = JsonConvert.DeserializeObject<RTMovieData>(jsonString, settings);

@Programmer在Unity C中提到“使用MiniJSON反序列化JSON”这一帖子作为这篇文章的重复。但是,这两篇文章根本没有关联。另一篇文章描述了使用不同JSON反序列化器的用户并且在获取要反序列化的数组时遇到了问题。我的问题特定于使用$ type属性来帮助反序列化器实例化子类,这在本文的标题中有说明。

1 个答案:

答案 0 :(得分:1)

解决方案:在我的JSON中,我需要添加&#34; Assembly-CSharp&#34;到$ type属性的值。

$type:"RTMoviePageWithSlides, Assembly-CSharp"

$type:"RTCharacterPage, Assembly-CSharp"