0

There is an application that was originally written in Ruby on Rails that provides API services to several mobile applications; management has decided to add the functionality of the RoR service to the main .NET-based project. OK, no big deal, we'll just duplicate the service calls in WebAPI right? How difficult can it be?

Apparently somebody on the Ruby side thought it would be a swell idea to put extra characters into the api response objects. I'm seeing things like:

{
    ...
    {"enabled?":true}
    ...
}

...so here I am, shaking my head at this, and hoping there is a technique to serialize .NET objects into JSON where variable names have question marks and whatnot. Is there a way to do this, or are we going to have to build custom serializers for each of these objects? Changing the mobile apps to consume more platform-friendly JSON is really not desirable at this point. We use JSON.Net, but if there's another way to do this, it'd be OK.

Jeremy Holovacs
  • 22,480
  • 33
  • 117
  • 254

1 Answers1

2

In your c# object, give your property a valid name (such as Enabled in this case) and then specify the JSON property name in the Name property of a DataMember attribute, or the PropertyName property of a JsonProperty attribute:

[DataContract]
public class MyClass
{
    [DataMember(Name="enabled?")]
    public bool Enabled { get; set; }
}

Or

public class MyClass
{
    [JsonProperty("enabled?")]
    public bool Enabled { get; set; }
}

If you use DataMemberAttribute, don't forget to add the DataContract attribute, and that data contract serialization is opt-in, so you'll need to add DataMember to all the attributes you want to serialize. Having done so, however, you'll gain compatibility with the DataContractSerializers, which might be useful down the road.

dbc
  • 104,963
  • 20
  • 228
  • 340