locked
Different object types in one collection - is it good practise for REST API? RRS feed

  • Question

  • User-1853917541 posted

    Hi,

    Question:  if I have response:
    {
    technics:
    [
    {
    "type" : "car", "maxspeed" : 250, "engine" : "gasoline"
    },
    {
    "type" : "refrigerator", "vol" : 380
    }
    ]
    }

    where technics collection contains objects of different types (note different attributes/properties). How common such scenario for well-designed API? Is it convenient typically for consumers (like even JScript in browsers) to support multiple object types in single collection? I understand it's mostly just contract question. But broader question is - how common and useful such contracts?

    Thanks!

    Tuesday, December 25, 2018 9:42 PM

All replies

  • User36583972 posted

    Hi Alex Petrov,

    where technics collection contains objects of different types (note different attributes/properties). How common such scenario for well-designed API? Is it convenient typically for consumers (like even JScript in browsers) to support multiple object types in single collection? I understand it's mostly just contract question. But broader question is - how common and useful such contracts?

    As far as I know, this is not common.

    If a response contains a JSON string with different types (note different attributes/propertie), we can use the ArrayList to receive the data. But, when we deserialize the Object, we need to know the order of the Different types, In this way, we can parse the type correctly.

    The following code for your reference.

     public IHttpActionResult PostGetCustomer([FromBody]ArrayList paramList)
            {
                
                if (paramList.Count > 0)
                {
                    Customer cus = Newtonsoft.Json.JsonConvert.DeserializeObject<Customer>(paramList[0].ToString());
                 
                    Order order = Newtonsoft.Json.JsonConvert.DeserializeObject<Order>(paramList[1].ToString());
                }
    
                 return Content(HttpStatusCode.OK, "1", Configuration.Formatters.JsonFormatter);
            }

    Best Regards,

    Yong Lu

    Wednesday, December 26, 2018 5:26 AM
  • User753101303 posted

    Hi,

    Uncommon but ultimately it depends on what you need. Do you have a real world scenario in mind ?  Think about how the client side will consume the additional data. Does it have to know about each type or each set of additional properties or it might be enough to have an collection for additional properties etc..

    .

    Wednesday, December 26, 2018 12:44 PM
  • User-474980206 posted
    While JavaScript can handle this easily, most other languages will be unable to de-serialize this response. They would need to use simple dictionaries of dictionaries or custom serializers.
    Wednesday, December 26, 2018 5:46 PM