DataMember Name property not working in entity framework

c# entity-framework-6 serialization

Question

I have Dto like this:

public class OptimizationNodeDto : IModelWithId
    {        
        public int Id { get; set; }

        [DataMember(Name = "parentId")]
        public int? ParentOptimizationNodeId { get; set; }

        [DataMember(Name = "name")]
        public string Text { get; set; }

        [DataMember(Name = "opened")]
        public bool IsOpened { get; set; }

        [DataMember(Name = "selected")]
        public SelectedStates SelectedState { get; set; }

        public List<OptimizationNodeDto> Children { get; set; }
    }

I want that when I send this object with any API it should give property name in JSON as like mentioned in DataMember but it's not happening. For ex.ParentOptimizationNodeId should be as parentId in JSON result. Here I am sending the Dto:

 [Route("{roleId}/Optimizations")]
        [HttpPost]
        public IHttpActionResult GetOptimizationList([FromUri]int roleId, [FromBody] FilterDto filter)
        {
            try
            {
                var groupManBo = _serviceLocator.Resolve<IRoleManagerBo>();
                return Ok(groupManBo.GetOptimization(roleId, this.ViewboxUser, filter));
            }
            catch (Exception ex)
            {
                return this.HandleError(ex);
            }
        }
1
1
3/17/2017 11:40:46 AM

Accepted Answer

DataMemberAttribute is ignored by both Json.NET and DataContractJsonSerializer unless [DataContract] is also applied to the type itself. From the docs:

Apply the DataMemberAttribute attribute in conjunction with the DataContractAttribute to identify members of a type that are part of a data contract.

Thus your DTO must look like:

[DataContract]
public class OptimizationNodeDto : IModelWithId
{
    [DataMember]
    public int Id { get; set; }

    [DataMember(Name = "parentId")]
    public int? ParentOptimizationNodeId { get; set; }

    [DataMember(Name = "name")]
    public string Text { get; set; }

    [DataMember(Name = "opened")]
    public bool IsOpened { get; set; }

    [DataMember(Name = "selected")]
    public SelectedStates SelectedState { get; set; }

    [DataMember]
    public List<OptimizationNodeDto> Children { get; set; }
}

Note that data contract serialization is opt-in so you now must also mark Id and Children with [DataMember].

5
3/19/2017 7:15:17 PM

Popular Answer

See .NET NewtonSoft JSON deserialize map to a different property name

[JsonProperty("new name")]
public string SomeColumn { get; set; }

However, this would assume you are using Newtonsoft as the JSON serializer. If you replaced it with a different one, you'd have to use the attributes specific to that serializer.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow