c# - 尝试使用JSON.NET和DataContractJsonSerializer反序列化JSON失败

标签 c# .net json json.net datacontractserializer

请帮助,我被困住了。
我有一个WCF服务,它返回如下内容:

{
   "GetDataRESTResult":
     [
       {"Key1":100.0000,"Key2":1,"Key3":"Min"},
       {"Key1":100.0000,"Key2":2,"Key3":"Max"}
     ]
}


并且我想反序列化它,但是无论使用什么(JSON.NET或DataContractJsonSerializer),我都会遇到错误。
当使用DataContractJsonSerializer时,我正在使用theis代码:

byte[] data = Encoding.UTF8.GetBytes(e.Result);
MemoryStream memStream = new MemoryStream(data);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<DataDC>));
List<DataDC> pricinglist = (List<DataDC>)serializer.ReadObject(memStream);


其中DataDC是我从WCF REST服务的服务引用中获取的数据协定,而我正在从其中获取JSON数据,而我得到的错误是InvalidCastException ...

尝试使用JSON.NET时,我遇到另一个异常,但是我仍然找不到任何东西,有人可以帮助吗?

编辑
  这是一个JSON.NET stacktrace:


  无法反序列化当前JSON对象(例如{“ name”:“ value”})
  成类型
  'System.Collections.Generic.List`1 [MyApp.MyServiceReference.DataDC]'
  因为该类型需要JSON数组(例如[1,2,3])进行反序列化
  正确地。要解决此错误,请将JSON更改为JSON数组
  (例如[1,2,3])或更改反序列化类型,使其成为常规
  .NET类型(例如,不是整数之类的原始类型,不是集合
  可以从JSON反序列化的类型(如数组或列表)
  宾语。也可以将JsonObjectAttribute添加到类型中以强制它
  从JSON对象反序列化。路径“ GetDataRESTResult”,第1行
  位置23。

最佳答案

下面的代码有效

string json = @" {""GetDataRESTResult"":[{""Key1"":100.0000,""Key2"":1,""Key3"":""Min""},{""Key1"":100.0000,""Key2"":2,""Key3"":""Max""}]}";

dynamic dynObj = JsonConvert.DeserializeObject(json);
foreach (var item in dynObj.GetDataRESTResult)
{
    Console.WriteLine("{0} {1} {2}", item.Key1, item.Key3, item.Key3);
}


您也可以使用Linq

var jObj = (JObject)JsonConvert.DeserializeObject(json);
var result = jObj["GetDataRESTResult"]
                .Select(item => new
                {
                    Key1 = (double)item["Key1"],
                    Key2 = (int)item["Key2"],
                    Key3 = (string)item["Key3"],
                })
                .ToList();

关于c# - 尝试使用JSON.NET和DataContractJsonSerializer反序列化JSON失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12699257/

相关文章:

c# - 如何在 C# 中显示该方法成功返回或失败而不返回值?

c# - 如何处理 dotnet 世界中的事务?

c# - 运算符重载放置和冗余

c# - 如何从 .net 中 wwwroot 内的多个文件夹提供 html 文件

c# - 将包含多个对象的json对象反序列化为列表

javascript - 使用 splice 删除 Javascript 对象数组中某个位置之后的所有元素

c# - 反序列化不一致的 JSON 属性

c# - Box2D body 速度上限?

c# - ListView 页脚行 - 水平滚动

c# - 如何在 C# 中比较两个字典元组值