如何发送JSON中嵌套对象数组括号网络API控制器 [英] how to send array brackets in json nested objects in web api controller

查看:169
本文介绍了如何发送JSON中嵌套对象数组括号网络API控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将数据发送到一个旅游门户网站的REST API。根据他们的文档,JSON数据必须按以下格式

I am sending data to a rest API of a travel portal. According to their documentation, the json data must be in the following format

{
    "EndUserIp": "192.168.10.10",
    "TokenId": "ac2751e9-4cc3-406f-b678-c947e4f57a00",
    "AdultCount": "1",
    "ChildCount": "0",
    "InfantCount": "0",
    "DirectFlight": "false",
    "OneStopFlight": "false",
    "JourneyType": "1",
    "PreferredAirlines": null,
    "Segments": [
    {
        "Origin": "DEL",
        "Destination": "BOM",
        "FlightCabinClass": "1",
        "PreferredDepartureTime": "2015-11-06T00: 00: 00",
        "PreferredArrivalTime": "2015-11-06T00: 00: 00"
    }],
    "Sources": [
        "6E"
    ]
}

我的模型

public class otherType
{
    public string Origin { get; set; }
    public string Destination { get; set; }
    public FlightCabinClass FlightCabinClass { get; set; }
    [DisplayFormat(NullDisplayText = "", DataFormatString = "{0:yyyy-MM-dd}")]
    public DateTime? PreferredDepartureTime { get; set; }
    [DisplayFormat(NullDisplayText = "", DataFormatString = "{0:yyyy-MM-dd}")]
    public DateTime PreferredArrivalTime { get; set; }
}

public class SearchForFlight
{
    public SearchForFlight()
    {
        JourneyList = new List<SelectListItem>();
        FlightCabinClassList = new List<SelectListItem>();
        Segments = new otherType();
    }
    public string EndUserIp { get; set; }
    public string TokenId { get; set; }
    public int AdultCount { get; set; }
    public int ChildCount { get; set; }
    public int InfantCount { get; set; }
    public bool DirectFlight { get; set; }
    public bool OneStopFlight { get; set; }
    public JourneyType JourneyType { get; set; }
    public string PreferedLines { get; set; }
    public otherType Segments { get; set; }
    [JsonIgnore]
    public IEnumerable<SelectListItem> FlightCabinClassList { get; set; }
    [JsonIgnore]
    public IEnumerable<SelectListItem> JourneyList { get; set; }
    public string Sources { get; set; }
}

以下code正确填充我的模型,但如果我包括在方括号,绑定失败。

The following code populates my model correctly, but if I include the square brackets, binding fails.

<script>
    $(document).ready(function () {                 
        $("#btnPost").click(function () {
            var sof = {
                AdultCount: $("#AdultCount").val(),
                JourneyType: $("#JourneyType :selected").text(),
                PreferredAirlines: null,
                Segments:
                {
                    Origin: $("#Segments_Origin").val(),
                    Destination: $("#Segments_Destination").val(),
                    FlightCabinClass: $("#FlightCabinClass").val(),
                    PreferredDepartureTime: $("#Segments_PreferredDepartureTime").val(),
                    PreferredArrivalTime: $("#Segments_PreferredArrivalTime").val(),
                }
            };

控制器

[System.Web.Http.HttpPost]
public async Task<HttpResponseMessage> SearchFlight([FromBody]SearchForFlight sof)
{
    string url = "http://api.tektravels.com/BookingEngineService_Air/AirService.svc/rest/Search/";
    using (HttpClient client = new HttpClient())
    {
        .....
    }
}

如何生成正确的格式和绑定的模式?

How do I generate the correct format and bind to the model?

推荐答案

该API格式表示的属性必须是 OTHERTYPE集合(模型只有一个对象)。此外,来源属性也是字符串

The API format means the the Segments property must be a collection of otherType (your model only has a single object). In addition the Sources property is also a collection of string.

您更改模型

public class SearchForFlight
{
    public SearchForFlight()
    {
        Segments = new List<otherType>();
        Sources = new List<string>();
    }
    ....
    public string PreferedLines { get; set; }
    public List<otherType> Segments { get; set; }
    [JsonIgnore]
    public IEnumerable<SelectListItem> FlightCabinClassList { get; set; }
    [JsonIgnore]
    public IEnumerable<SelectListItem> JourneyList { get; set; }
    public List<string> Sources { get; set; }
}

再假设你只想要编辑一个和一个来源,然后在GET方法,添加一个目标是每个集合

and then assuming your only wanting to edit one Segments and one Sources, then in the GET method, add one object to each collection

SearchForFlight model = new SearchForFlight();
model.Segments.Add(new otherType());
model.Sources.Add(string.Empty);
....
return View(model);

和在视图中,使用循环生成集合的HTML

and in the view, use for loops to generate the html for the collections

@for(int i = 0; i < Model.Segments.Count; i++)
{
    @Html.LabelFor(m => m.Segments[i].Origin)
    @Html.TextBoxFor(m => m.Segments[i].Origin)
    @Html.ValidationMesageFor(m => m.Segments[i].Origin)
    .... // other properties of otherType
}

请注意,这将产生 ID 属性,如 ID =Segments_0__Origin让你的脚本将需要

Note that this will generate id attributes such as id="Segments_0__Origin" so your script would need to be

Segments:
{
    Origin: $("#Segments_0__Origin").val(),
    Destination: $("#Segments_0__Destination").val(),
    ....

但有没有必要手动生成你的JavaScript对象,你的AJAX可以简单地

however there is no need to generate you javascript object manually, and your ajax can be simply

$.ajax({
    ....
    data: $('form').serialize(),
    ....

,所以它使用默认的应用程序/ x-WWW的形式urlen coded不会设置的contentType 选项;字符集= UTF-8

and do not set the contentType option so it uses the default application/x-www-form-urlencoded; charset=UTF-8

这篇关于如何发送JSON中嵌套对象数组括号网络API控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆