簡體   English   中英

使用 C# MVC 訪問 Cosmos Db JSON 數據

[英]Access Cosmos Db JSON data using C# MVC

我正在嘗試使用 c# MVC Web 應用程序顯示 Cosmos db JSON Subitems。 但我收到一個錯誤:

無法從 System.DateTime 強制轉換或轉換為 WebApplication1.Models.Entry。

JSON:

 "DataTypeId": 1,
"IPaddress": "192.168.2.177",
"id": "d1b81653-b7a5-4d79-85ea-79c01f43f747",
"PhoneNo": "0417518324",
"LastContact": {
    "EnvLog": "2019-09-07T19:41:08",
    "Ping": "2020-01-09T12:10:09",
    "SpdLog": "2019-09-07T19:41:08"
},
"SpeedLog": true,
"DeviceModelId": 2,
"DisconnectEvents": 9,

模型:

    public class DeviceMap
{

    [JsonProperty(PropertyName = "id")]
    public string Id { get; set; }

    [JsonProperty(PropertyName = "IPaddress")]
    public string IPaddress { get; set; }

    [JsonProperty(PropertyName = "SpeedLog")]
    public bool SpeedLog { get; set; }

    [JsonProperty(PropertyName = "LastContact")]
    public Entry LastContact { get; set; }
}

 public class Entry

{

    [JsonProperty(PropertyName = "EnvLog")]
    public DateTime EnvLogtime { get; set; }

    [JsonProperty(PropertyName = "Ping")]
    public DateTime Ping { get; set; }

    [JsonProperty(PropertyName = "SpdLog")]
    public DateTime SpdLog { get; set; }
}
}

控制器:

public class DeviceMapController : Controller
{
    [ActionName("Index")]
    public async Task<ActionResult> Map1Async()
    {
        string empty = "Unknown";

        var items = await DocumentDBRepository<DeviceMap>.GetMap1Async(d => d.Id != null, d => d.Lat != empty);
        if (Convert.ToInt32(User.GroupId()) != 200) 
            {
                items = items.Where(d => d.GroupId == Convert.ToInt32(User.GroupId()));

        }

        return View(items);

    }
}

看法:

             @foreach (var item in Model)
                    {


                        if ((@item.IPaddress == "192.168.2.14") || (@item.IPaddress == "192.168.2.13") || (@item.IPaddress == "192.168.2.15") || (@item.IPaddress == "192.168.2.16")) { }
                        else
                        {

                            //SideId string
                            string siteId = null;
                            string newsiteId = null;
                            if (item.IPaddress != "0")
                            {

                                int index = item.IPaddress.IndexOf('.') + 1;
                                int space = item.IPaddress.IndexOf('.', index + 1);
                                int space2 = item.IPaddress.IndexOf('.', space + 1);
                                int end = item.IPaddress.Length;
                                if (index > 0) { siteId = item.IPaddress.Substring(space + 1, end - space - 1); newsiteId = siteId.Replace('.', '-'); }
                            }
                           //  string Cutoff =Html.DisplayFor(modelItem => item.LastContact.Ping).ToString();
                         // DateTime day = DateTime.Parse(Cutoff.Value,"dd/MM/yyyy HH:mm:ss", CultureInfo.CurrentCulture);

                          DateTime myday =Html.DisplayFor(modelItem => item.LastContact.Ping);
                            DateTime now = DateTime.Now;
                            DateTime yesterday = now.AddDays(-7);
                            DateTime d;
                       //  DateTime.TryParseExact(myday,@"dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal,out d);


                          // if (Html.DisplayFor(modelItem => item.LastContact.Ping) != null) { d = DateTime.Parse(myday, "dd/MM/yyyy HH:mm:ss", CultureInfo.CurrentCulture); } else { myday = DateTime.ParseExact("08/04/2000 14:00:02", "dd/MM/yyyy HH: mm:ss", CultureInfo.CurrentCulture); }

                            string a = @item.Name;



                            <tr>

                                <td>

                                    @if (a.Length > 50) { a = a.Substring(0, 50); }



                                        @if (item.GroupId != 82)
                                        {

                                            if (myday <= DateTime.Now.AddDays(-7))
                                            {<h4>@myday</h4>
                                                    <img src="/Content/Images/trafficlight-red2.png" width="20" height="20"><a href="@Url.Action("DevicePage", "Device", new { item.DeviceId })"><h6>@a..</h6></a>
                                            }
                                            else
                                            {<img src="/Content/Images/trafficlight-green1.png" width="20" height="20"><a href="@Url.Action("DevicePage", "Device", new { item.DeviceId })"><h6>@a..</h6></a>
                                            }
                                        }


                                        else
                                        {


                                            if (myday <= DateTime.Now.AddDays(-7))
                                            {
                                                <img src="/Content/Images/trafficlight-red2.png" width="20" height="20"><a href="@Url.Action("Form", "TARP", new { item.DeviceId })"><h6>@a..</h6></a>
                                            }
                                            else
                                            {<img src="/Content/Images/trafficlight-green1.png" width="20" height="20"><a href="@Url.Action("Form", "TARP", new { item.DeviceId })"><h6>@a..</h6></a>

                                            }

                                        }

                                        @if (item.IPaddress != "0")
                                        {<p>Site Id: @newsiteId;</p>}
                                    @if (item.LastPing != null)
                                    {
                                        <p>
                                            Last Contact: @Html.DisplayFor(modelItem => item.LastContact.Ping), @Html.DisplayFor(modelItem => item.BatVoltage)V

                                        </p>}


我想顯示 Ping 日期和時間。 請幫忙。 此外,如果您有關於如何調用不同樣式的 JSON 數據的資源,請提供鏈接以供參考。 謝謝你。

public class DeviceMap
{
    [JsonProperty(PropertyName = "id")]
    public string Id { get; set; } // Suggestion: Change this to 'Guid' instead of string

    [JsonProperty(PropertyName = "IPaddress")]
    public string IPaddress { get; set; }

    [JsonProperty(PropertyName = "SpeedLog")]
    public bool SpeedLog { get; set; }

    [JsonProperty(PropertyName = "LastContact")]
    public Entry LastContact { get; set; }
}

public class Entry

{
    [JsonProperty(PropertyName = "EnvLog")]
    public DateTime EnvLogtime { get; set; }

    [JsonProperty(PropertyName = "Ping")]
    public DateTime Ping { get; set; }

    [JsonProperty(PropertyName = "SpdLog")]
    public DateTime SpdLog { get; set; }
}

如果您選擇DateTime作為Entry中每個變量的類型,您的 LastContact 將正確反序列化。

測試

我使用了你的 json 並將其轉換為 DeviceMap 對象來測試它並確保上述工作正常。

{
  "DataTypeId": 1,
  "IPaddress": "192.168.2.177",
  "id": "d1b81653-b7a5-4d79-85ea-79c01f43f747",
  "PhoneNo": "0417518324",
  "LastContact": {
    "EnvLog": "2019-09-07T19:41:08",
    "Ping": "2020-01-09T12:10:09",
    "SpdLog": "2019-09-07T19:41:08"
  },
  "SpeedLog": true,
  "DeviceModelId": 2,
  "DisconnectEvents": 9
}

並在我的主要內容中使用以下內容反序列化它以確保它正常工作。

DeviceMap map = JsonConvert.DeserializeObject<DeviceMap>(json);

地圖中數據的屏幕截圖。

在類中定義類型絕對更好,以便在反序列化時,您不必將其解析為它們應該是的類型。 反序列化器應該為您處理這個問題,並將您的字符串轉換為您的類的類型,如果它是可轉換的,例如,自動將字符串轉換為GuidDateTime

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM