将 JSON 粘贴为类重复项,将数字元素粘贴为唯一类



我有以下来自Shopify的JSON部分:

{
    "orders": [
        {
            "total_line_items_price_set": {
                "shop_money": {
                    "amount": "281.96",
                    "currency_code": "USD"
                },
                "presentment_money": {
                    "amount": "281.96",
                    "currency_code": "USD"
                }
            },
            "total_discounts_set": {
                "shop_money": {
                    "amount": "0.00",
                    "currency_code": "USD"
                },
                "presentment_money": {
                    "amount": "0.00",
                    "currency_code": "USD"
                }
            },
        },

当我使用"将 JSON 粘贴为类"功能时,我得到像"shop_money"和"presentment_money"这样的元素重复并作为单独的类编号。

    public class Total_Line_Items_Price_Set
    {
        public Shop_Money shop_money { get; set; }
        public Presentment_Money presentment_money { get; set; }
    }
    public class Shop_Money
    {
        public string amount { get; set; }
        public string currency_code { get; set; }
    }
    public class Presentment_Money
    {
        public string amount { get; set; }
        public string currency_code { get; set; }
    }
    public class Total_Discounts_Set
    {
        public Shop_Money1 shop_money { get; set; }
        public Presentment_Money1 presentment_money { get; set; }
    }
    public class Shop_Money1
    {
        public string amount { get; set; }
        public string currency_code { get; set; }
    }
    public class Presentment_Money1
    {
        public string amount { get; set; }
        public string currency_code { get; set; }
    }

我是 JSON 的新手,以及如何在 C# 中将其表示为类 - 这似乎是错误的。是否有可能获得更好的结果?

溶液:

根据Zakk Diaz的回答,我删除了每个重复和编号的类。这样做后,我成功地反序列化并使用了订单对象数组。


    public class Orders
    {
        public Order[] orders { get; set; }
    }
    public class Order
    {
        // [...]
    }
    class Program
    {
        static void Main(string[] args)
        {
            // [...]
            Orders testOrders = JsonConvert.DeserializeObject<Orders>(responseFromServer);
            Console.WriteLine(testOrders.orders[0].id);
            Console.WriteLine(testOrders.orders[0].total_line_items_price_set.shop_money.amount);
            Console.WriteLine(testOrders.orders[0].line_items[1].price_set.shop_money.amount);
        }
    }

在大多数情况下看起来不错,您可以删除这些类并在"Total_Discounts_Set"中重命名它们

    public class Shop_Money1
{
    public string amount { get; set; }
    public string currency_code { get; set; }
}
public class Presentment_Money1
{
    public string amount { get; set; }
    public string currency_code { get; set; }
}

相关内容

  • 没有找到相关文章

最新更新