【问题标题】:Failing JSON Deserialization in VS2012 C#VS2012 C#中的JSON反序列化失败
【发布时间】:2015-07-09 00:06:19
【问题描述】:

使用 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();

            }
        }
    }
}

感谢您的帮助!

【问题讨论】:

    标签: c# json datacontractserializer json-deserialization


    【解决方案1】:

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

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

    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);
    
        // Using JSON.NET to deserialize object
         var responseDataSerialized = JsonConvert.DeserializeObject<RootObject>(content);
    
        // visual display of content
        Console.WriteLine(content);
    
        // Here's using DataContractSerializer
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(RootObject));
        using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(content)))
        {
            // deserialize the JSON object using the JSONResponseData type.
            var responseData = (RootObject)serializer.ReadObject(ms);
    
            // Set breakpoint here to monitor responseData value
            Console.ReadLine();
    
        }
    }
    

    【讨论】:

    • 感谢您提供有用的见解!这解决了我的问题!
    • 您可以将此标记为答案。它也会帮助其他用户。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多