VS2012 C#

时间:2015-07-09 00:06:20

标签: c# json datacontractserializer json-deserialization

将VS 2012与C#一起使用,我试图从网站的api反序列化json响应数据,但序列化后我得到空值。我尝试了几种不同的反序列化方法,它们都返回空值。任何建议将不胜感激!

以下是详细信息:

示例JSON响应数据:

{"response":{"metaInfo":{"timestamp":"2015-07-06T20:44:51Z","mapVersion":"8.30.58.159","moduleVersion":"7.2.58.0-1179","interfaceVersion":"2.6.13"},"route":[{"routeId":"AHAACAAAAB4AAAA6AAAAnwAAAJUAAAB42mOYysDAxMQABM6p7Z2hoaGpDFCQmBQqZsdib8Pw/z9E4MN+BiTABcThf3LOMDHk1U9A0ZgC1GjCiVdj3cKXQYxAi+GC/3s/ZruBJRvYgJSAHgBjgBtIVTckbg==","mode":{"type":"fastest","transportModes":["car"],"trafficMode":"enabled","feature":[]},"leg":[{"length":4014,"travelTime":612}]}],"language":"en-us"}}

JSON数据类:

我最初使用json2csharp.com转换来从上面的json文本构建类结构。我将生成的类名重命名为JSONResponseData。后来我在看到带有这种表示法的MSDN示例后添加了所有[DataMember]条目。但无论有没有[DataMember],返回的反序列化值都没有区别。更改生成的json类名称也没有区别。

using System.Collections.Generic;
using System.Runtime.Serialization;

namespace JsonApiClient
{
/// <summary>
/// Class to represent the JSONResponseData
/// </summary>
[DataContract]
public class JSONResponseData
{
    [DataMember]
    public string timestamp { get; set; }
    [DataMember]
    public string mapVersion { get; set; }
    [DataMember]
    public string moduleVersion { get; set; }
    [DataMember]
    public string interfaceVersion { get; set; }
}

public class Mode
{
    [DataMember]
    public string type { get; set; }
    [DataMember]
    public List<string> transportModes { get; set; }
    [DataMember]
    public string trafficMode { get; set; }
    [DataMember]
    public List<object> feature { get; set; }
}

public class Leg
{
    [DataMember]
    public int length { get; set; }
    [DataMember]
    public int travelTime { get; set; }
}

public class Route
{
    [DataMember]
    public string routeId { get; set; }
    [DataMember]
    public Mode mode { get; set; }
    [DataMember]
    public List<Leg> leg { get; set; }
}

public class Response
{
    [DataMember]
    public JSONResponseData metaInfo { get; set; }
    [DataMember]
    public List<Route> route { get; set; }
    [DataMember]
    public string language { get; set; }
}

public class RootObject
{
    [DataMember]
    public Response response { get; set; }
}
}

主程序:

using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using Newtonsoft.Json;
using System.Xml;
using System.Xml.Serialization;
using System.Diagnostics;
using System.Net;

namespace JsonApiClient
{
    class Program
    {
        private const string baseUrl = "http://route.cit.api.here.com/routing/7.2/calculateroute.json?app_id={0}&app_code={1}&waypoint0={2}&waypoint1={3}&mode=fastest;car;traffic:enabled&avoidseasonalclosures=true&metricsystem=imperial&routeattributes=none,lg,ri&legattributes=none,le,tt";

        static void Main(string[] args)
        {
            String appid = "DemoAppId01082013GAL";
            String appcode = "AJKnXv84fjrb0KIHawS0Tg";
            String waypoint0 = "geo!52.5,13.4";
            String waypoint1 = "geo!52.5,13.45";

            // Customize URL according to geo location parameters
            String url = string.Format(baseUrl, appid, appcode, waypoint0, waypoint1);

            // Syncronous Consumption
            var syncClient = new WebClient();
            var content = syncClient.DownloadString(url);

            // visual display of content
            Console.WriteLine(content);

            //
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(JSONResponseData));
            using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(content)))
            {
                // deserialize the JSON object using the JSONResponseData type.
                var responseData = (JSONResponseData)serializer.ReadObject(ms);

                // Set breakpoint here to monitor responseData value
                Console.ReadLine();

            }
        }
    }
}

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您使用的是错误的类型,即JSONResponseData。在DataContractSerializer中使用RootObject作为类型,并将结果强制转换为RootObject。

这是更新后的代码。我已经包含了JSON.Net序列化,这比使用DataContractSerializer更快更好。

class MyParam {
  public $_;
  public $attrName;

  public function __construct($paramValue, $attrValue)
  {
    $this->_ = $paramValue;
    $this->attrName = $attrValue;
  }
}

$soap->param = new MyParam("value", "attributeName");