E
E
Egor Mikheev2017-08-08 17:58:37
ASP.NET
Egor Mikheev, 2017-08-08 17:58:37

How to set a setter for a nested collection of objects?

Hello, how to correctly parse json object into a class.
Client data:

{"contacts":[
    {
        "FirstName": "Vasya",
        "SecondName": "Petrov",
        "Phones": [ "79854571245"]
    }, 
    {
        "FirstName": "Petya",
        "Company": "SDD",
        "Phones": ["79854571241","79854571246"]
}]
}

I accept request:
public ActionResult Update(List<Contact> contacts)
 {   
   return Json(new { state = contacts });
 }

The class structure into which the request is parsed
public class Contact
    {

        public Contact()
        {
            var Phones = new List<Phone>();
        }
        public int id { get; set; }

        public string FirstName { get; set; }

        public string SecondName { get; set; }

        public string Company { get; set; }

        public string UserId { get; set; }
        [ForeignKey("UserId")]
        public virtual ApplicationUser User { get; set; }

        public ICollection<Phone> Phones { get; set; }

        public DateTime DateAdd { get; set; } = DateTime.Now;
    }
}

phone
public class Phone
    {

        public int id { get; set; }
        public string Tel { get; set; }

        public int ContactId { get; set; }

        [ForeignKey("ContactId")]
        public virtual Contact Contact { get; set; }

        public DateTime DateAdd { get; set; } = DateTime.Now;
    }
}

It is natural that the structure of request not absolutely corresponds to classes. Is it possible to implement a custom constructor to fill in the corresponding fields of the Phones collection

Answer the question

In order to leave comments, you need to log in

2 answer(s)
H
heartdevil, 2017-08-08
@heartdevil

Look here
look

E
eRKa, 2017-08-08
@kttotto

In your case, the field Phoneswill try to deserialize to ICollection<string>, but because in the model ICollection<Phone>, then there will probably be an exception about the impossibility of converting.
One of the solutions is the answer above, implement your own JsonConverter(according to the image as in the link, there are small changes for your case) and mark the field Phoneswith an attribute with this converter.
But I wouldn't do that. For me, there is a difference between the models that go between requests and the models with which the logic works. Therefore, one model for your request with a type field ICollection<string>(I would have this model called ContractDTO), and then I would already map it into Contract, in which the field Poneswill be of type ICollection<Phone>. You can do this either with the automaper library , or by hand, throughmodelDTO.Select(x => new Model { ... });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question