使用Newtonsoft和C#</string,>反转字典<string,object =“”>

时间:2015-04-03 14:15:58

标签: c# json.net json-deserialization

我试图解析来自服务器的Json响应。 我设法重新创建服务器响应,我可以用Newtonsoft解析这个响应。 我的问题来自我的字典(字符串,JSONNode),这是我所有解析对象的基类。

这是我的代码

[Serializable]
public class JSONNode
{
    public string Type { get; set; }
    public string Id { get; set; }
}

[Serializable]
public class Cache : JSONNode
{
    public Dictionary<string, JSONNode> Elements { get; set; }
}

[Serializable]
public class Parking : JSONNode
{
    public List<Car> Cars { get; set; }
}

public class House : JSONNode
{
    public int Number { get; set; }
}

[Serializable]
public class Car : JSONNode
{
    public JSONNode Back { get; set; }
}

public static void Main()
{
    var Cache = new Cache()
    {
        Type = "Cache",
        Id = "Cache",
        Elements = new Dictionary<string, JSONNode>() {
            {"Parking", new Parking(){
            Type = "Parking",
            Id = "Parking",
            Cars = new List<Car>(){
                new Car(){
                Type="MyType1",
                Id = "3",
                Back = null},
                new Car(){
                Type="MyType2",
                Id = "3",
                Back = null}}
                }
            },
            {"House", new House(){
                Type="House",
                Id="House",
                Number=156}
            }
        }
    };
    var json = new JavaScriptSerializer().Serialize(Cache);
    var jsonSettings = new Newtonsoft.Json.JsonSerializerSettings
    {
    TypeNameHandling = Newtonsoft.Json.TypeNameHandling.All,
    TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple
    };
    var reCache = Newtonsoft.Json.JsonConvert.DeserializeObject<Cache>(json, jsonSettings);
}

有没有办法用Newtonsoft解析这类信息?我需要这个库,因为它与Unity兼容,我稍后会需要它。

编辑:正如我想的那样,没有办法巧妙地解析词典。作为一种解决方法,我使用JSON解析器(如SimpleJSON)将我的数据解析为树。

1 个答案:

答案 0 :(得分:0)

*大多数(根据我的经验)JSON序列化程序只能处理字典,只要它们处理原始(和字符串)键/值,换句话说,你不必构建自己的处理程序或返回2单独列表。

这样可行:

var Cache = new Cache()
{
    Type = "Cache",
    Id = "Cache",
    ElementKeys = new List<string> {
        {"Parking", "House" };
    ElementValues = new List<JSONNode>{
        new Parking(){
        Type = "Parking",
        Id = "Parking",

        Cars = new List<Car>(){
            new Car(){
            Type="MyType1",
            Id = "3",
            Back = null},
            new Car(){
            Type="MyType2",
            Id = "3",
            Back = null}}
            },
        new House(){
        Type="House",
        Id="House",
        Number=156}

    }
 };

您必须像这样更改Cache课程:

[Serializable]
public class Cache : JSONNode
{
    public List<string> ElementKeys { get; set; }
    public List<JSONNode> ElementValues { get; set; }
}
相关问题