简体   繁体   English

反序列化来自 Json C# 的嵌套字典

[英]Deserialize Nested Dictionary in from Json C#

I have a class something like this我有一个 class 这样的东西

public class A{
    public Guid userId { get; set; }
    public Guid businessId { get; set; }
    public Dictionary<int, long> rights { get; set; }
}

And I want to covert this json to this class我想把这个 json 转换成这个 class

    {
    "userId": "dc2af693-72e1-49a7-80aa-6416c6536bdf",
    "businessId": "0110eea4-7a47-4a7c-95ea-10547ab49652",
    "rights": "{\"19\":1,\"17\":15,\"18\":1,\"23\":1,\"1\":31,\"20\":3,\"3\":1,\"16\":0}",
   }

But when Im trying to convert it with NewtonSoft.Json但是当我试图用 NewtonSoft.Json 转换它时

JsonConvert.DeserializeObject<A>(json);

I get the following error Cannot Cast System.string to System.Dictionary<int,long> What happens is that my rights get converted to a string something like this我收到以下错误Cannot Cast System.string to System.Dictionary<int,long>发生的事情是我的权利被转换为类似这样的字符串

"{"19":1, "17":15, "18":1, ..., "16":0}"

If I deserialize this string again it works as I desire is there better method to do this.如果我再次反序列化这个字符串,它会按照我的意愿工作,有没有更好的方法来做到这一点。

Since the rights is in string format, you can add custom JsonConverter which converts the string to dictionary由于rights是字符串格式,您可以添加自定义JsonConverter将字符串转换为字典

public class A
{
    public Guid userId { get; set; }
    public Guid businessId { get; set; }
    [JsonConverter(typeof(RightsSerializer))]
    public Dictionary<int, long> rights { get; set; }
}

Here is the RightsSerializer这是 RightsSerializer

public class RightsSerializer : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(Dictionary<int, long>);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null) return null;

        var jt = JToken.Load(reader);
        return JsonConvert.DeserializeObject<Dictionary<int, long>>(jt.Value<String>());
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        serializer.Serialize(writer, value);
    }
}

And DeserializeObject和反序列化对象

var json = File.ReadAllText("json1.json");
var result = JsonConvert.DeserializeObject<A>(json);

changing the class to something like this will help.将 class 更改为这样的内容会有所帮助。 althoutgh you need to make code better than this.尽管您需要使代码比这更好。

        public class A
    {
        public Guid userId { get; set; }
        public Guid businessId { get; set; }

        //[JsonConverter(typeof(Dictionary<int, long>))]
        public string rights { get; set; }

        public Dictionary<int, long> rightss => JsonConvert.DeserializeObject<Dictionary<int, long>>(rights);
    }

You can't do it without deserializing twice, but you could hide it with a private subclass.如果不反序列化两次就无法做到这一点,但是您可以使用私有子类隐藏它。

public class A {
   public Guid userId {get;set;}
   public Guid businessId {get;set;}
   public Dictionary<int, long> rights {get;set;}

   private class B {
      public Guid userId {get;set;}
      public Guid businessId {get;set;}
      public string rights {get;set;}
   }

   private B b;

   public A (string json) {
      var o = new JsonSerializerOptions();
      o.AllowTrailingCommas = true;
      b = JsonSerializer.Deserialize<B>(json, o);
      userId = b.userId;
      businessId = b.businessId;
      rights = JsonSerializer.Deserialize<Dictionary<int, long>>(b.rights,o);
   }
}

Usage with test in fiddle:小提琴测试的用法:

Fiddle小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM