使用JSON.Net反序列化包含字典的字节数组[重复]

问题描述 投票:-2回答:1

我面临以下情况。我的一个项目正在抛出一个包含以下对象的事件:

public class MyEvent : BaseEvent
{
   public long Id { get; set; }
   public Dictionary<string, long> Pairs { get; set; }
}

我收到了这个事件,并在接收器端读取数据为byte []。我必须阅读任何通用事件的当前代码是:

public static T Decode(byte[] data)
{
    var serializer = JsonSerializer.Create(new JsonSerializerSettings
    {
        TypeNameHandling = TypeNameHandling.Objects,
        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
    });

    using (var stream = new MemoryStream(data))
    {
        using (var sr = new StreamReader(stream, Encoding.UTF8))
        {
            var jr = new JsonTextReader(sr);
            var aux = Encoding.UTF8.GetString(data);
            return serializer.Deserialize(jr, typeof(T)) as T;
        }
    }
}

其中T是我的班级MyEvent。不幸的是抛出的异常是:

无法将当前JSON数组(例如[1,2,3])反序列化为类型'System.Collections.Generic.Dictionary`2 [System.String,System.Int64]',因为该类型需要JSON对象(例如{“name “:”value“})正确反序列化。要修复此错误,请将JSON更改为JSON对象(例如{“name”:“value”})或将反序列化类型更改为数组或实现集合接口的类型(例如ICollection,IList),例如List从JSON数组反序列化。 JsonArrayAttribute也可以添加到类型中以强制它从JSON数组反序列化。路径'OperationTimePairs',第1行,第61位。

我读它的方式是收到的对象没有正确的格式..但是,如果我尝试通过var aux = Encoding.UTF8.GetString(data)读取它;我可以看到结构是正确的。知道我该如何解决这个问题?谢谢!

编辑:

Json示例:

{  
   "Timestamp":"\/Date(1540996292134)\/",
   "Pairs":[  
      {  
         "Key":"first time",
         "Value":28
      },
      {  
         "Key":"second time",
         "Value":30
      },
      {  
         "Key":"third time",
         "Value":101
      },
      {  
         "Key":"operation time",
         "Value":231
      }
   ],
   "Id":123637
}
c# arrays json serialization json.net
1个回答
1
投票

我认为你的类与json字符串结构不匹配。

给出以下json字符串:

{  
   "Timestamp":"\/Date(1540996292134)\/",
   "Pairs":[  
      {  
         "Key":"first time",
         "Value":28
      },
      {  
         "Key":"second time",
         "Value":30
      },
      {  
         "Key":"third time",
         "Value":101
      },
      {  
         "Key":"operation time",
         "Value":231
      }
   ],
   "Id":123637
}

您可以更改模型以匹配json结构,如下所示:

public class MyEvent : BaseEvent
{
    public long Id { get; set; }
    public List<KeyValuePair<string, long>> Pairs { get; set; }

    [JsonIgnore]
    public Dictionary<string, long> PairsDictionary
    {
        get
        {
            if (Pairs == null)
            {
                return new Dictionary<string, long>();
            }

            return Pairs.ToDictionary(pair => pair.Key, pair => pair.Value);
        }
    }
}

public class BaseEvent
{
    public DateTime Timestamp { get; set; }
}

请注意:

  • PairsDictionary是基于Pairs的非序列化属性
  • 鉴于您没有提供BaseEvent的类定义,我将假设它只有1个属性

测试反序列化:

string json = @"{  
""Timestamp"":""\/Date(1540996292134)\/"",
""Pairs"":[  
    {  
     ""Key"":""first time"",
     ""Value"":28
    },
    {  
     ""Key"":""second time"",
     ""Value"":30
    },
    {  
     ""Key"":""third time"",
     ""Value"":101
    },
    {  
     ""Key"":""operation time"",
     ""Value"":231
    }
],
""Id"":123637
}";

MyEvent eventData = JsonConvert.DeserializeObject<MyEvent>(json);

或者作为替代(使用泛型):

T data = JsonConvert.DeserializeObject(json, typeof(T)) as T;
© www.soinside.com 2019 - 2024. All rights reserved.