2

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"
      ]
    }
  ]
}
1
  • 4
    Note that the @ in the C# code is not actually considered to be part of the identifier, so the names of those property is actually context and type. The @ is used to tell the compiler that any syntax rules that would make the following word a keyword should be ignored and consider it as an identifier, but the @ isn't added to the identifier. In other words, it isn't Json.Net that is removing the @, it is the C# compiler that isn't adding them because they mean something else. Commented Sep 10, 2018 at 10:22

2 Answers 2

7

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

Comments

1

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 ; }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.