【问题标题】:Failed to display API response with label无法显示带有标签的 API 响应
【发布时间】:2018-07-29 19:55:31
【问题描述】:

我是 ASP.NET 的新手。最近,我创建了自己的 api。因此,我决定创建一个 web 表单来测试 api。但是,没有显示响应,我相信我所做的一切都是正确的。

我的网页表单代码

using System;
using Newtonsoft.Json;
using FoodBlog.Model;


namespace FoodBlog
{
    public partial class Home : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var weatherData = new WeatherData();
            var webClient = new System.Net.WebClient();
            var json = webClient.DownloadString("https://1ibewdli19.execute-api.us-east-2.amazonaws.com/Working/blogid/1");
            string replacedString = json.Replace("<", "");
            string replacedString1 = replacedString.Replace(">", "");
            WeatherData wdata = JsonConvert.DeserializeObject<WeatherData>(replacedString1);

            Label1.Text = wdata.description;
        }
    }
}

型号:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace FoodBlog.Model


{

    public class WeatherData
    {
        public string description { get; set; }
        public string iconDesc { get; set; }
        public string TimeStamp { get; set; }

    }
}

JSON 数据工作正常(使用 Postman)

    {
    "id": "<Humid and mostly cloudy throughout the day.>",
    "icon": "<partly-cloudy-day>",
    "time": "<1532448000>"
}

【问题讨论】:

  • 使用邮递员,或通过浏览器的开发者工具检查响应/请求(通常是 F12)。
  • JSON 和模型不匹配
  • @Nkosi Aha,感谢您的提示!

标签: c# asp.net json amazon-web-services serialization


【解决方案1】:

您的 JSON 字符串无法匹配您的 model,您可以尝试使用 JsonProperty 属性来映射您的 JSON 字符串和模型属性。

public class WeatherData
{
    [JsonProperty("id")]
    public string description { get; set; }
    [JsonProperty("icon")]
    public string iconDesc { get; set; }
    [JsonProperty("time")]
    public string TimeStamp { get; set; }
}

或者使用这个类你会得到 JSON 数据。

public class WeatherData
{
    public string id { get; set; }
    public string icon { get; set; }
    public string time { get; set; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-17
    • 2023-03-05
    • 1970-01-01
    相关资源
    最近更新 更多