530

I have some data in a C# DataSet object. I can serialize it right now using a Json.net converter like this

DataSet data = new DataSet();
// do some work here to populate 'data'
string output = JsonConvert.SerializeObject(data);

However, this uses the property names from data when printing to the .json file. I would like to change the property names to be something different (say, change 'foo' to 'bar').

In the Json.net documentation, under 'Serializing and Deserializing JSON' → 'Serialization Attributes' it says "JsonPropertyAttribute... allows the name to be customized". But there is no example. Does anyone know how to use a JsonPropertyAttribute to change the property name to something else?

(Direct link to documentation)

Json.net's documentation seems to be sparse. If you have a great example I'll try to get it added to the official documentation. Thanks!

1

4 Answers 4

936

You could decorate the property you wish controlling its name with the [JsonProperty] attribute which allows you to specify a different name:

using Newtonsoft.Json;
// ...

[JsonProperty(PropertyName = "FooBar")]
public string Foo { get; set; }

Documentation: Serialization Attributes

11
  • 4
    @culix, yes, it does require using a model. A DataSet is a weakly typed structure, so talking about property names for it is not very logical. Jan 10, 2012 at 6:50
  • 104
    As a shorthand, you can also do [JsonProperty("FooBar")] Feb 16, 2015 at 5:49
  • 4
    @DarinDimitrov is there a way to do this without Json .NET ?
    – CH81
    Dec 31, 2015 at 17:39
  • 16
    Using a model is easy though, just take a sample of your JSON and Paste it into an empty .cs file using "Paste Special" -> "Paste JSON as Classes". -- It's built in to Visual Studio. -- From there, you basically just need to set things up as title case / rename stuff to use .NET naming conventions, etc. (using a title case converter for the former, and the JsonProperty attribute for the latter). Oct 24, 2016 at 23:36
  • 3
    @Homer That wouldn't work in this case, since the point is to be able to use a name different from the member.
    – Trisibo
    Jul 29, 2020 at 3:46
107

If you don't have access to the classes to change the properties, or don't want to always use the same rename property, renaming can also be done by creating a custom resolver.

For example, if you have a class called MyCustomObject, that has a property called LongPropertyName, you can use a custom resolver like this…

public class CustomDataContractResolver : DefaultContractResolver
{
  public static readonly CustomDataContractResolver Instance = new CustomDataContractResolver ();

  protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
  {
    var property = base.CreateProperty(member, memberSerialization);
    if (property.DeclaringType == typeof(MyCustomObject))
    {
      if (property.PropertyName.Equals("LongPropertyName", StringComparison.OrdinalIgnoreCase))
      {
        property.PropertyName = "Short";
      }
    }
    return property;
  }
}

Then call for serialization and supply the resolver:

 var result = JsonConvert.SerializeObject(myCustomObjectInstance,
                new JsonSerializerSettings { ContractResolver = CustomDataContractResolver.Instance });

And the result will be shortened to {"Short":"prop value"} instead of {"LongPropertyName":"prop value"}

More info on custom resolvers here

5
  • 4
    This is a better solution if your class to serialize is declared in another assembly that includes a different version of Newtonsoft.Json package. (it may not even throw any error). The DefaultContractResolver must be put in the same assembly where JsonConvert.Serialize() method is used.
    – Artemious
    Jan 29, 2018 at 23:32
  • 2
    I'm working with an vendor's API that has a common object that is used by multiple API functions. In only one of the API calls, one property on the common object must be serialized to a slightly different name (e.g. clientid versus client_id). This answer was the perfect solution to my problem.
    – quaabaam
    Dec 8, 2020 at 19:21
  • It does not change the member names in lower levels other than root. Only the main members are monitored but the children of root members are not changed this way.
    – VSB
    Oct 5, 2023 at 13:29
  • @VSB - Do you mean when the root and children are of the same type?
    – StingyJack
    Oct 9, 2023 at 22:27
  • Root contains list of elements of same type but those element itself composed of several objects inside it. the name of fields inside those inner child are not changed and updated.
    – VSB
    Oct 17, 2023 at 12:02
9

There is still another way to do it, which is using a particular NamingStrategy, which can be applied to a class or a property by decorating them with [JSonObject] or [JsonProperty].

There are predefined naming strategies like CamelCaseNamingStrategy, but you can implement your own ones.

The implementation of different naming strategies can be found here: https://github.com/JamesNK/Newtonsoft.Json/tree/master/Src/Newtonsoft.Json/Serialization

5
  • 5
    If you're able, please share an example of a custom NamingStrategy implementation Dec 10, 2018 at 17:36
  • 2
    Of course... not. You should have done it by yourself, but I'll spare you the time to tell you that you simply have to inherit newtonsoft.com/json/help/html/… You can see the existing classes implementation, and create your own one.
    – JotaBe
    Dec 11, 2018 at 11:09
  • 4
    Thanks - I should have updated my comment: in fact, thanks to the glory that is GitHub, one can use one of Newtonsoft's own implementations as an example, say, this one Dec 11, 2018 at 16:34
  • 24
    @JotaBe, that's not the spirit of stackoverflow. And as a programmer who just wants to get my job done, frankly, it would have been a thousand times better for me to to lift the code you might have provided. And you would have got my vote as well. I have 18 years coding experience, and I'm ranked by TripleByte as "expert" in c#. Not EVERY problem needs to be left as an "exercise for the reader". Sometimes we just want to do our job and move on.
    – bboyle1234
    Apr 2, 2019 at 0:52
  • 5
    I agree with you, and I don't usually write this kind of comment. However, I can assure that, in this case, looking at the linked code is way better than any explanation I can give. And json.net is a very well documented open source library. Included link to the implementations (perfect examples)
    – JotaBe
    Apr 2, 2019 at 14:54
4

You can directly use

[JsonProperty(Name = "access_token")]
public string AccessToken { get; set; }

or

[JsonProperty("access_token")]
public string AccessToken { get; set; }

and serialize using Newthonsoft.Json library will be detect how change it

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.