将JSON反序列化为Class

时间:2016-01-21 07:53:46

标签: c# deserialization

我正在尝试对此字符串进行反序列化:

storage = "{\"1\":{\"1\":\"aaa\"},\"2\":{\"1\":\"bbb\"}}";

它有效:

var LocalStorageOBJ1 = JsonConvert.DeserializeObject<Dictionary<DataModels.StoragePrimaryKeys,
                                                    Dictionary<DataModels.StorageSecondaryKeys, string>>>(storage);

但我想用一个类来做,比如:

var LocalStorageOBJ = JsonConvert.DeserializeObject<MyClass>(storage);

MyClass是:

public class DataModels
{
    public enum StoragePrimaryKeys
    {
        Login = 1,
        Account = 2
    };

    public enum StorageSecondaryKeys
    {
        JobTitle = 1,
        JobId = 2,
        JobLocation = 3,
        RenewDate = 4,
        ExpirationDate = 5
    };
}


public class MyClass
{
    public Dictionary<DataModels.StoragePrimaryKeys, ForiegnData> PrimaryDictionary { get; set; }
}
public class ForiegnData
{
    public Dictionary<DataModels.StorageSecondaryKeys, string> ForeignDictionary { get; set; }
}

不幸的是,当我反序列化时,我得到了null。

任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:3)

MyClass不是

Dictionary<DataModels.StoragePrimaryKeys, Dictionary<DataModels.StorageSecondaryKeys, string>>

MyClass HAS

Dictionary<DataModels.StoragePrimaryKeys, Dictionary<DataModels.StorageSecondaryKeys, string>>

所以你应该正确封装JSON字符串:

{\"PrimaryDictionary\" : {\"1\":{\"1\":\"aaa\"},\"2\":{\"1\":\"bbb\"}}}