gpt4 book ai didi

c# - 将json数据反序列化为c#中的列表

转载 作者:太空宇宙 更新时间:2023-11-03 23:02:43 25 4
gpt4 key购买 nike

我正在调用一个外部网络服务,这是我在发布到他们的服务器后得到的响应:

{
"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>或类似的。不清楚您有什么 list ,但这自然是一本字典。然后将其嵌套在顶层的字典中。

示例代码:

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

关于c# - 将json数据反序列化为c#中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42507444/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com