locked
How to change WEB API to accept a JSON Array for multiple entries? RRS feed

  • Question

  • User1121128150 posted

    HI

    I am using the below very simple code for a simple insert when a JSON message comes in the body of the message, but what do I need to change in order to accept a JSONarray in the body with multiple entries?

     [HttpPut]
            public void put([FromBody] orp OrderR)
            {
                _context.orp.Add(OrderR);
                _context.SaveChanges();
            }

    Also I am assuming the JSON array format should be

    [
    {
    JSON DAta here
    },
    {
    next JSON Object here
    }
    ]



    Wednesday, July 6, 2016 4:36 PM

Answers

  • User765422875 posted

    As an example, your json array would look similar to the following:

    [{
    	"OrderName": "ggg",
    	"OrderNumber": "WS-C3650-24PS-S",
    	"Quantity": "1"
    }, {
    	"OrderName": "asdfasdf",
    	"OrderNumber": "WS-C3650-24PS-S",
    	"Quantity": "3"
    }]

    And you would pass in a list (as an example):

    [FromBody]List<OrderR> orders

    Your loop would look similar to the following:

    foreach(var orp in orders)
    {
       _context.orp.Add(orp);
    }



    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, July 6, 2016 6:22 PM

All replies

  • User1992938117 posted

    Try as below

    [HttpPut]
    public void put([FromBody] string[] OrderR)
    {
    	string seperator = ",";
            string data = string.Join(seperator,OrderR.ToList<string>());
    	// other code
    }

    May help https://www.roelvanlisdonk.nl/?p=3505 

    Wednesday, July 6, 2016 6:01 PM
  • User1121128150 posted

    ok but how do I then convert that data string back to a OrderR object so I can run 

    _context.orp.Add(data);

    and do I loop through it ?

    I apologise but the answer is a bit short for me to take on and test it

    Wednesday, July 6, 2016 6:20 PM
  • User765422875 posted

    As an example, your json array would look similar to the following:

    [{
    	"OrderName": "ggg",
    	"OrderNumber": "WS-C3650-24PS-S",
    	"Quantity": "1"
    }, {
    	"OrderName": "asdfasdf",
    	"OrderNumber": "WS-C3650-24PS-S",
    	"Quantity": "3"
    }]

    And you would pass in a list (as an example):

    [FromBody]List<OrderR> orders

    Your loop would look similar to the following:

    foreach(var orp in orders)
    {
       _context.orp.Add(orp);
    }



    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, July 6, 2016 6:22 PM
  • User1121128150 posted

    this seems to work but how do I then loop through the list because the add code expects a single orp object?

    _context.orp.Add(orp);

    And right now it says cannot convert from List to orp object

    So I guess I need to some how loop through the List Orders ? but I am unsure how

    Wednesday, July 6, 2016 6:43 PM
  • User1121128150 posted

    WOrked it out, now testing with this code

    public void put([FromBody] List<orp> orders)
    {
    foreach (orp order in orders)
    {
    _context.orp.Add(order);
    _context.SaveChanges();
    }
    }
    
    Will report back how it goes



    Wednesday, July 6, 2016 6:48 PM
  • User1121128150 posted

    Hi

    This works beautifully, thank you for taking the time to guide me on this, I really do appreciate it and the solution is so wonderfully simple as well

    Wednesday, July 6, 2016 6:52 PM
  • User765422875 posted

    I've edited my answer. Use a simple ForEach loop.

    Wednesday, July 6, 2016 6:56 PM
  • User765422875 posted

    Sure.

    You you can call SaveChanges outside of the loop. It will persist all changes to the database at once vs. inserting into the database for every item. Also consider wrapping your entity framework code in a transaction.

    If you are using EF 6, then you can do something similar to the following:

    http://www.entityframeworktutorial.net/entityframework6/transaction-in-entity-framework.aspx

    http://www.binaryintellect.net/articles/165bb877-27ee-4efa-9fa3-40cd0cf69e49.aspx

    Wednesday, July 6, 2016 7:21 PM
  • User1121128150 posted

    Yeah I moved the save outside the loop already, I thought transaction was default behavior? I am using EF7/1 CORE hoever they call it these days

    Wednesday, July 6, 2016 7:31 PM
  • User765422875 posted

    I haven't used EF Core yet so I can't speak to it.

    In EF 6, yes the default is that it wraps Insert, Update or Delete operations in a transaction, whenever you execute SaveChanges().

    The additional support allows for finer control - if required.

    Wednesday, July 6, 2016 7:40 PM
  • User36583972 posted

    Hi mattdouhan@outlook.com,

    Glad you found the solution, the following proposal aims to give you more help.

    You can also use a single Object that wraps the multiple parameters/entries.

    Web API:

         public multipleObject PostAlbum(multipleObject request)
            {
                var album = request.o1;
                var userToken = request.o2;
                return new multipleObject()
                {
                     o1= album,
                     o2= userToken
                };
            }
    
      public class multipleObject
        {
            public ob1 o1 { get; set; }
            public ob2 o2 { get; set; }
        }
    
        public class ob1
        {
            public int LOG_ID { get; set; }
        }
        public class ob2
        {
            public int LOG_ID { get; set; }
        }

    Call this method on the client and send it up as JSON.

        var o1 = {
                LOG_ID: "1"
            }
            var o2 = {
                LOG_ID: "1"
            }
            $.ajax(
            {
                url: "http://localhost:1190/api/Postmultiple",
                type: "POST",
                contentType: "application/json",
                data: JSON.stringify({ ob1: o1, ob2: o2 }),
                success: function (result) {
                    alert(result.Result);
                }
            });

    Best Regards,

    Yohann Lu

    Thursday, July 7, 2016 2:57 AM