1

I use c# and Newtonsoft.Json library for serialization and deserialization of json.

I have a class like this

public class Animal
{
    [JsonProperty(PropertyName = "Dog")]
    public Key value {get;set;}
}

if i instantiate it as

Animal a = new Animal{ Key = "bobby" };

and i serialize it i'll have a json like

{
    "dog": "bobby"
}

can i change the PropertyName of the serialization dynamically? for instance, what if i want to put "Bird" or "Cat" instead of "Dog"?

Pablo Romeo
  • 11,298
  • 2
  • 30
  • 58
CaTourist
  • 711
  • 3
  • 9
  • 21
  • Maybe writing a custom JsonConverter for it, but is that even a real scenario? It seems like @dotnetstep's solution would give you the JSON you want and would make more sense than trying to use a Property for something other than what it's really meant to represent. – Pablo Romeo Dec 06 '14 at 00:51
  • You may be interested in this [similar question](http://stackoverflow.com/q/19792274/10263). – Brian Rogers Dec 07 '14 at 02:01

1 Answers1

2
public class Animal
{
    public KeyValuePair<string,string> value {get;set;}
}

Animal a = new Animal { value = new KeyValuePair("dog","boddy")};

if you want bird

Animal a = new Animal { value = new KeyValuePair("bird","bird1")};
dotnetstep
  • 17,065
  • 5
  • 54
  • 72
  • This doesn't produce JSON in the format requested by the OP. It produces JSON that looks like `{"value":{"Key":"dog","Value":"boddy"}}`. See https://dotnetfiddle.net/P51YnE. You would need a dictionary rather than a single key/value pair for the desired effect. See [Serialize a Dictionary](http://www.newtonsoft.com/json/help/html/SerializeDictionary.htm). – dbc Dec 16 '15 at 22:41