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

时间:2019-07-14 19:01:29

标签: c# json visual-studio-2019

我有来自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);
        }
    }

1 个答案:

答案 0 :(得分:1)

大多数情况下看起来不错,您可以删除这些类并在“ 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; }
}