T和DataContractJsonSerializer反序列化

T和DataContractJsonSerializer反序列化

本文介绍了尝试使用JSON.NET和DataContractJsonSerializer反序列化JSON失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

plz help, I'm stuck.I have a WCF service which returns something like this:

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

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

and I would like to deserialize it, but whatever I use (JSON.NET or DataContractJsonSerializer) I'm getting errors.When using DataContractJsonSerializer I'm using theis code:

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 ...

where DataDC is the data contract which I've got from the service reference of the WCF REST service I'm getting the JSON data from, and the error I'm getting is InvalidCastException...

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

Trying to use JSON.NET I get another exception, but still nothing I can figure out, can anyone help please?

编辑 这是JSON.NET堆栈跟踪:

EDIT Here's a JSON.NET stacktrace:

推荐答案

以下代码有效

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

You can also use 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();

这篇关于尝试使用JSON.NET和DataContractJsonSerializer反序列化JSON失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 18:31