5

I have a library I'm interfacing with which I have absolutely no control over. The objects are formatted with property names like this:

{"my property": "my value"}

and

{"my-property": "my value"}

Using json.net I can add an attribute to the properties in the class that represents each message to map those property names to a property in my class:

public class MyClass
{
  [JsonProperty(PropertyName="my-prop")]
  public String MyProperty {get; set;}
}

This is fine, but the issue is that I have to use these 'magic strings' on a large number of classes and I really despise magic strings.

The bottom line:

Is there any way to change all of these properties into a C# readable string so as to have json.net map those properties automatically?

i.e.:

{"my property": "my value"}

Should change to:

{"MyProperty": "my value"}

During deserialization, which would then flow that value to the MyProperty member in MyClass without annotating the property with a hard coded string value.

Robert Petz
  • 2,718
  • 4
  • 23
  • 52
  • I just answered a [very similar question](http://stackoverflow.com/q/19792274/10263) where I discuss two approaches: using a custom JsonConverter, and modifying the Json.Net source code. I think the same solution(s) apply in your case. – Brian Rogers Nov 10 '13 at 03:40
  • Excellent answer @BrianRogers...I was trying something similar but I'm not familiar enough with what JsonConverter does and so I wasn't quite approaching it correctly...I'll give this a try tomorrow and get back to you, but it seems promising – Robert Petz Nov 10 '13 at 05:49
  • @BrianRogers Yup, looks like that worked perfectly (the JsonConverter approach). If you want credit for the answer (especially since you didn't get any before) you can post your answer here and I'll mark it as correct – Robert Petz Nov 13 '13 at 06:17

0 Answers0