【问题标题】:C# Capture webrequest request via json and Serializer into c# objectC# 通过 json 和 Serializer 将 webrequest 请求捕获到 c# 对象中
【发布时间】:2016-06-08 17:05:08
【问题描述】:

我正在与一个 RESTful API 通信并尝试通过 c# 对象捕获响应。

我之前使用 WebRequest 和 Get 成功捕获了响应,但使用 Post 和 Streamreader 我认为我犯了一些愚蠢的错误。

如果有人可以帮助我确定我的 JavaScriptSerializer 的正确结构并且我是否正确请求信息以捕获 Json 对象,我将不胜感激?

编辑:我应该道歉 - 我收到“无效 JSON 原语:”的序列化代码错误。

         public void UpdatePosition(string SessionID, int AssetID, string SerialNumber)
    {
        positions Positions = GeneratePositions(AssetID);
        var request = (HttpWebRequest)WebRequest.Create("https://some.website.com/webservices/command/v1/Position?Session=" + SessionID + "&Serial=" + SerialNumber + "&Positions=" + Positions.Latitude + "," + Positions.Longitude + "," + Positions.SpeedKmh + "," + Positions.Course + "," + Positions.Utcdatetime + "," + Positions.IgnitionState);

        request.ContentType = "application/json";
        request.Method = "POST";
        request.KeepAlive = false;
        request.Timeout = 30000;
        request.ContentLength = 0;
        request.Accept = "application/json";

        var response = (HttpWebResponse)request.GetResponse();
        Reply2 info = new Reply2();
        using (var streamReader = new StreamReader(response.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            JavaScriptSerializer parser = new JavaScriptSerializer();
            info = parser.Deserialize<Reply2>(result);
        }

        return;
    }            

    public class UpdatePostionResponse
    {
        public responseCode ResponseCode { get; set; }
    }

    public class Reply2
    {
        public  UpdatePostionResponse response { get; set; }
    }

        public class responseCode
    {
        public string Code { get; set; }
        public string Message { get; set; }
    }

使用 Postman 我获得了成功,但无法正确捕获响应。 回应:

<UpdatePostionResponse xmlns="http://tempuri.org/">
<ResponseCode xmlns:a="http://schemas.datacontract.org/2004/07/Command.DataContracts" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <a:Code>UpdatePositionSuccess</a:Code>
    <a:Message>Positions updated.</a:Message>
</ResponseCode>

【问题讨论】:

  • 服务以 XML 而不是 json 响应,并且忽略了您的接受标头。需要进一步了解该服务才能说更多。
  • @PaulSwetz 谢谢保罗,至少它为我提供了一个追求的途径。

标签: c# json asp.net-mvc api webrequest


【解决方案1】:

结果正如 Paul Swetz 指出的那样,服务器返回的不是 json,而是 XML。

感谢 Paul 强调这一点,感谢 POSTMAN 帮助我识别并向服务器编码人员展示以纠正它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-04
    • 2017-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多