-1

I'm trying to send a JSON message to facebook that they call a game.achievement but I wanted to create the object using an AnonymousType before Posting. The problem is one of the fields is "game:points" (with the colon). As you can see I've used the @ prefix for the object field but it doesn't work for the game:points field. It gets underlined in red and won't compile.

        var paramsJson = new
            {
                privacy = new { value = "ALL_FRIENDS" },
                @object = new
                {
                    app_id = "my app id",
                    type = "game.achievement",
                    title = "Test",
                    @"game:points" = 100,
                    description = "Test",
                    image = "img.png"
                }
            };

I've tried many varieties of @, double quotes etc. Is it possible or do I need to just use a StringBuilder for this?

deejbee
  • 1,148
  • 11
  • 17
  • A member-name obviously can´t contain a colon. However you can of course name it `points` or even `@object` (where the `@` just means that you want to use an identifier which has the same name as a reserved keyword (`object` is a built-in .NET-type, as `int`, or `string`). – MakePeaceGreatAgain Jul 25 '17 at 20:03
  • 1
    What you are asking goes beyond simple serialization. You could use a library like Newtonsoft, create your own class and tell it how to serialize the object: https://stackoverflow.com/questions/8796618/how-can-i-change-property-names-when-serializing-with-json-net – JuanR Jul 25 '17 at 20:03
  • @HimBromBeere I wish I could just use a different field name but it has been defined by FB. – deejbee Jul 25 '17 at 20:24

1 Answers1

0

Why don't you just use a dictionary?

var postData = new Dictionary<string, object>
{
    {"game:points", 100}
}

Presumably you're going to have to serialize your object to Post it regardless of how it's constructed. Serializing this to JSON would result in the same structure. Alternatively, just do as other's have suggested and create a class for your payload. You can then use Newtonsoft to indicate alternative names for serialization.

public class GameAchievement
{
   [JsonProperty("game:points")]
   public int Points {get; set;}
}
Jesse Carter
  • 20,062
  • 7
  • 64
  • 101
  • Thanks Jesse, a Dictionary was all I needed. I knew resorting to a StringBuilder was a bad idea :) – deejbee Jul 26 '17 at 10:56