Answer the question
In order to leave comments, you need to log in
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"]
}]
}
public ActionResult Update(List<Contact> contacts)
{
return Json(new { state = contacts });
}
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;
}
}
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;
}
}
Answer the question
In order to leave comments, you need to log in
In your case, the field Phones
will 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 Phones
with 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 Pones
will 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 questionAsk a Question
731 491 924 answers to any question