Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebApi - Deserializing and serializing alternate property names

I'm trying to figure out how I can specify alternate property names with ASP.NET WebApi - and have it work for deserialization + serialization, and for JSON + XML. I've only uncovered partial solutions so far.

I want to expose the property names as lower case with underscores, and (for example's sake) have different internal names:

External:

  • field-one
  • field-two

Internal:

  • ItemOne
  • ItemTwo

For testing, here's a POST controller action that just relays what it receives:

// POST api/values
public TestSerialization Post([FromBody]TestSerialization value)
{
    return value;
}

And a test entity:

public class TestSerialization
{
    [DataMember(Name = "field_one")] // Doesn't appear to change anything
    public string ItemOne { get; set; }

    [JsonProperty(PropertyName = "field_two")] // Only works for serialization in JSON mode
    public string ItemTwo { get; set; }
}

So far, I've found:

  • [DataMember(Name = "x")] has no effect on serialization in either direction
  • [JsonProperty(Name = "x")] works on serialization (the returning value) when using JSON. (It's a JSON.NET attribute, the default serializer).

For test data, I submit 4 properties, to see which value gets deserialized, and what the property name is on deserialization

  • ItemOne = "Value A"
  • ItemTwo = "Value B"
  • field-one = "Correct 1"
  • field-two = "Correct 2"

How can I achieve this?

like image 280
Overflew Avatar asked Mar 18 '14 22:03

Overflew


1 Answers

Some of your findings/conclusions are incorrect...you can try the following instead:

This should work for both default Xml & Json formatters of web api and for both serialization & deserialization.

[DataContract]
public class TestSerialization
{
    [DataMember(Name = "field_one")]
    public string ItemOne { get; set; }

    [DataMember(Name = "field_two")]
    public string ItemTwo { get; set; }
}

The following should work for Json formatter only and for both serialization & deserialization.

public class TestSerialization
{
    [JsonProperty(PropertyName = "field_one")]
    public string ItemOne { get; set; }

    [JsonProperty(PropertyName = "field_two")]
    public string ItemTwo { get; set; }
}
like image 88
Kiran Avatar answered Oct 03 '22 17:10

Kiran