简体   繁体   中英

how to pass json array information to net core web api

I am building a web api with net core, I need to use the post method to save the information of a json file, the drawback is that the json file has an array and I do not know how to send the information to the stored procedure in sql so that it save the information the json file is this

"buyer": { // 
   "firstName": "fabio",
   "lastName": "gomez",
   "documentType": 0, // Puede ser 0: DNI, 1: Pasaporte o 2: Carnet de Extranjeria
   "documentNumber": "01234567", // Permitir letras para pasaportes extranjeros
   "phoneNumber": "51912345678",
   "email": "hnos@gmail.com"
 },
 "passengers": [{ // En el primer pasajero, pueden repetirse los datos del comprador
     "seat": 1,
     "firstName": "pedro",
     "lastName": "peres", // Considerar nueva campo 
     "secondLastName": "martinez",
     "documentType": 0, // Puede ser 0: DNI, 1: Pasaporte o 2: Carnet de Extranjeria
     "documentNumber": "15588",
     "age": 42,
     "gender": 0, // Puede ser 0: Masculino, 1: Femenino
   },
   {
     "seat": 2,
     "firstName": "Adriana",
     "lastName": "gomez",
     "secondLastName": "lopez",
     "documentType": 1, // Puede ser 0: DNI, 1: Pasaporte o 2: Carnet de Extranjeria
     "documentNumber": "XY01234567",
     "age": 40,
     "gender": 1, // Puede ser 0: Masculino, 1: Femenino
   }
 ],

This json must enter the system via post, which I use the following driver

[HttpPost]
  public async Task<IActionResult> Post([FromBody] List<string> valores)
        {
             await _repository.Insert(valores);
            return Ok();


        }

try doing something with ado.net but it doesn't work

  public async Task Insert(List<string> parametros)
        {
            using (SqlConnection sql = new SqlConnection(_connectionString))
            {
                using (SqlCommand cmd = new SqlCommand("sp_insertarpasajero", sql))
                {
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    //cmd.Parameters.Add(new SqlParameter("@Id", parametros));

                    await sql.OpenAsync();
                    await cmd.ExecuteNonQueryAsync();
                    return;
                }
            }
        }

I do not know how to pass the information from the controller that receives the post to an object or datatable and then use it in a stored procedure I appreciate your collaboration

For you json file, you should create a model object to accept the json data.The following is my working demo, you could refer to and make the modification on your project:

Model

 public class Buyer
{
    public int Id { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int DocumentType { get; set; }
    public string DocumentNumber { get; set; }
    public string PhoneNumber { get; set; }

    public string Email { get; set; }
}
 public class Passenger
{
    public int Id { get; set; }
    public int Seat { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string SecondLastName { get; set; }
    public int DocumentType { get; set; }
    public string DocumentNumber { get; set; }
    public string Age { get; set; }

    public int Gender { get; set; }
}

 public class OrderInfo
{
    public Buyer Buyer { get; set; }
    public List<Passenger> Passengers { get; set; }
}

Stored procedure , use OPENJSON (Transact-SQL)

CREATE PROCEDURE [dbo].[sp_insertpassenger]
  @json NVARCHAR(max)
AS
  INSERT INTO Passenger(
  Seat,FirstName,LastName,SecondLastName,
  DocumentType,DocumentNumber,Age,Gender)

  Select *
  FROM OPENJSON(@json ,'$.Passengers')
  WITH(
  Seat int '$.Seat',
  FirstName nvarchar(50) '$.FirstName',
  LastName nvarchar(50) '$.LastName',
  SecondLastName nvarchar(50) '$.SecondLastName',
  DocumentType int  '$.DocumentType',
  DocumentNumber nvarchar(50) '$.DocumentNumber',
  Age int '$.Age',
  Gender int '$.Gender' );
RETURN 0

Controller and repository method

[HttpPost]
    public async Task<IActionResult> Post([FromBody] OrderInfo values)
    {
        await _repository.Insert(values);
        return Ok();
    }

public async Task Insert(OrderInfo parameter)
    {

        using (SqlConnection sql = new SqlConnection(connectionString))
        {
            using (SqlCommand cmd = new SqlCommand("sp_insertpassenger", sql))
            {
                cmd.CommandType = System.Data.CommandType.StoredProcedure;

                var json = JsonConvert.SerializeObject(parameter);
                cmd.Parameters.Add(new SqlParameter("@json", json));

                await sql.OpenAsync();
                await cmd.ExecuteNonQueryAsync();
                return;
            }
        }
    }

Result在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM