[英]Deserialize json data into list in c#
我正在調用外部Web服務,這是我在發布到他們的服務器后得到的響應:
{
"status":200,
"data":{
"h21":{
"total_price":{
"acacia":{
"available":0,
"price":null,
"availability":false
},
"maple":{
"available":7,
"price":2399.0,
"availability":true
}
}
},
"h17":{
"total_price":{
"mahogany":{
"available":1,
"price":1899.0,
"availability":true
},
"oak":{
"available":0,
"price":null,
"availability":false
},
"maple":{
"available":6,
"price":1649.0,
"availability":true
}
}
}
}
}
我希望將此響應轉換為列表。 我使用jsontocsharp在線轉換器生成類並使用下面的代碼:
var Jsonresult = JsonConvert.DeserializeObject<Sstageback.Models.Sstage.treeboRoomTypes.RootObject>(JsonReplace);
但事情是我的是一個動態的JSON響應,它可以隨着時間的推移而改變。
注意:我從服務器獲得的響應是酒店及其房間可用性,因此在生成類時我無法使用單個類文件生成,因為酒店ID可能也會更改房間類型,其可用性也會發生變化。
示例:h21是一個酒店ID,total_price有房間類型詳細信息,h17是下一個酒店,total_price有房間類型詳細信息。
基本上, TotalPrice
應該是Dictionary<string, Availability>
或類似的。 目前尚不清楚你的名單是什么,但這自然是一本字典。 然后,它嵌套在頂層的字典中。
示例代碼:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
public class Response
{
public int Status { get; set; }
public Dictionary<string, Hotel> Data { get; set; }
}
public class Hotel
{
[JsonProperty("total_price")]
public Dictionary<string, Room> TotalPrice { get; set; }
}
public class Room
{
public int Available { get; set; }
public decimal? Price { get; set; }
public bool Availability { get; set; }
}
class Test
{
static void Main(string[] args)
{
var text = File.ReadAllText("test.json");
var response = JsonConvert.DeserializeObject<Response>(text);
foreach (var pair in response.Data)
{
Console.WriteLine($"Key: {pair.Key}");
foreach (var nestedPair in pair.Value.TotalPrice)
{
var room = nestedPair.Value;
Console.WriteLine($" {nestedPair.Key}: {room.Available}/{room.Price}/{room.Availability}");
}
}
}
}
輸出:
Key: h21
acacia: 0//False
maple: 7/2399.0/True
Key: h17
mahogany: 1/1899.0/True
oak: 0//False
maple: 6/1649.0/True
您需要制作與響應相對應的DTO模型。 只要類型保持不變(int保持為int且字符串保持字符串),屬性的值可以更改,這沒有問題。
您的對象可能如下所示:
public class Room{
public int Available { get; set;}
public int Price { get; set; }
public bool availability { get; set; }
}
public class Hotel{
public string Name { get; set; }
public List<Room> Rooms { get; set; }
}
您應該轉換序列化和反序列化。 這只是一個示例,您希望您的模型與您的JSON 100%相同。
為了在Models和DTO之間輕松轉換,您可以使用AutoMapper: http : //automapper.org/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.