Tom Beech
Tom Beech

Reputation: 2389

Serialising C# object and preserving property name

I am trying to post a serialised object to a web service. The service requires the property names 'context' and 'type' to be formatted as '@context' and '@type' other wise it won't accept the request.

Newtonsoft JSON.NET is removing the '@' from the property names 'context' and 'type' and i need them to carry through into the JSON. Can anyone assist?

Here is the class I am using

public class PotentialAction
{
    public string @context { get; set; }
    public string @type { get; set; }
    public string name { get; set; }
    public IList<string> target { get; set; } = new List<string>();
}

Here is the JSON that it is being converted to:

{
  "potentialAction": [
   {
      "context": "http://schema.org",
      "type": "ViewAction",
      "name": "View in Portal",
      "target": [
        "http://www.example.net"
      ]
    }
  ]
}

But this is what I need it to serialise to:

{
  "potentialAction": [
   {
      "@context": "http://schema.org",
      "@type": "ViewAction",
      "name": "View in Portal",
      "target": [
        "http://www.example.net"
      ]
    }
  ]
}

Upvotes: 2

Views: 283

Answers (2)

user2047029
user2047029

Reputation:

There are some attributes you can use to define what the field name should be.

https://www.newtonsoft.com/json/help/html/SerializationAttributes.htm

You would be using it like so: [JsonProperty(PropertyName = "@context")] Public string context { get; set ; }

Upvotes: 1

DavidG
DavidG

Reputation: 118957

In C#, the @ prefix on a variable is used to allow you to use a reserved word, for example @class. So it will be effectively ignored. To control the property name for serialisation, you need to add the JsonProperty attribute to your model:

public class PotentialAction
{
    [JsonProperty("@context")]
    public string @context { get; set; }

    [JsonProperty("@type")]
    public string @type { get; set; }

    public string name { get; set; }
    public IList<string> target { get; set; } = new List<string>();
}

Upvotes: 7

Related Questions