Сериализация нескольких классов моделей / Просмотр моделей в один Json - PullRequest
0 голосов
/ 09 апреля 2020

Я использую asp. Net Core (EF / MVC) и использую API через httpRequestMessage StringContent.

Как я могу сделать для сериализации несколько классов моделей / Просмотр моделей в single Json (Newtonsoft. Json), как пример ниже?

Я буду очень признателен за пример кода или что-то еще ...

{
    "seller_id": "6eb2412c-165a-41cd-b1d9-76c575d70a28",
    "amount": 100,
    "order": {
        "order_id": "6d2e4380-d8a3-4ccb-9138-c289182818a3",
        "product_type": "service"
    },
    "customer": {
        "customer_id": "customer_21081826",
        "email": "customer@email.com.br",
        "billing_address": {
            "street": "Av. Brasil",
            "number": "1000",
            "city": "Porto Alegre", 
            "state": "RS",
            "postal_code": "90230060"
         }
    },
    "device": {
       "ip_address": "127.0.0.1",
       "device_id": "hash-device-id"
    }
}

1 Ответ

1 голос
/ 09 апреля 2020

Создание моделей, как показано ниже:

public class RootoClass
{
    public Guid Seller_id { get; set; }
    public int Amount { get; set; }
    public Order Order { get; set; }
    public Customer Customer { get; set; }
    public Device Device { get; set; }
}

public class Order
{
    public Guid Order_id { get; set; }
    public string Product_type { get; set; }
}

public class Customer
{
    public string Customer_id { get; set; }
    public string Email { get; set; }
    public Billing_Address Billing_address { get; set; }
}

public class Billing_Address
{
    public string Street { get; set; }
    public string Number { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Postal_code { get; set; }
}

public class Device
{
    public string Ip_address { get; set; }
    public string Device_id { get; set; }
}

Использование Newtonsoft.Json.JsonConvert:

public string Index()
{
    var model = new RootoClass()
    {
        Seller_id = new Guid("6eb2412c-165a-41cd-b1d9-76c575d70a28"),
        Amount = 100,
        Order = new Order()
        {
            Order_id = new Guid("6d2e4380-d8a3-4ccb-9138-c289182818a3"),
            Product_type = "service"
        },
        Customer = new Customer()
        {
            Customer_id = "customer_21081826",
            Email = "customer@email.com.br",
            Billing_address = new Billing_Address()
            {
                Street = "Brasil",
                Number = "1000",
                City = "Porto Alegre",
                State = "RS",
                Postal_code= "90230060"
            }
        },
        Device = new Device()
        {
            Ip_address= "127.0.0.1",
            Device_id= "hash-device-id"
        }

    };
    var json = JsonConvert.SerializeObject(model);
    return json;
}
...