1

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);
            }
        }
Dipak
  • 1,199
  • 4
  • 21
  • 43

2 Answers2

7

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].

dbc
  • 104,963
  • 20
  • 228
  • 340
2

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.

Community
  • 1
  • 1
Daniel Lorenz
  • 4,178
  • 1
  • 32
  • 39