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"?

2
  • 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. Commented Dec 6, 2014 at 0:51
  • You may be interested in this similar question. Commented Dec 7, 2014 at 2:01

1 Answer 1

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")};
Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't produce JSON in the format requested by the OP. It produces JSON that looks like {"value":{"Key":"dog","Value":"boddy"}}. See dotnetfiddle.net/P51YnE. You would need a dictionary rather than a single key/value pair for the desired effect. See Serialize a Dictionary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.