18

I'm getting a JSON feed from Google's data API and a lot of the property names start with a $ character (dollar sign).

My problem is that I can't create a C# class with a variable name starting with a dollar sign, it's not allowed by the language. I'm using JSON.NET from Newtonsoft to convert JSON to C# objects. How can I get around this problem?

Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
Johnathan Sewell
  • 739
  • 10
  • 26

3 Answers3

30

You could try using the [JsonProperty] attribute to specify the name:

[JsonProperty(PropertyName = "$someName")]
public string SomeName { get; set; }
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
19

firas489 was on the right track that $ indicates metadata, not an actual data field. However the fix is actually to do this:

JsonSerializerSettings settings = new JsonSerializerSettings();
settings.MetadataPropertyHandling = MetadataPropertyHandling.Ignore;            

Set the metadata handling to ignore, and then you can serialize/deserialize the property using the PropertyName attribute:

[JsonProperty("$id")]
public string Id { get; set; }
Greg Ennis
  • 14,917
  • 2
  • 69
  • 74
  • 1
    This should be the accepted answer. Perhaps it has changed since OP posted, but current Json.Net (13.0) requires setting metadata handling to "ignore" to solve this issue. – whobetter Jul 12 '22 at 14:15
4

Those items with the dollar sign ($) are usually meant to be metadata and NOT fields. When JSON.NET serializes an object and you tell it to handle the object types, it will insert $ items that denotes metadata for correct deserialization later on.

If you want to treat the $ items as metadata, use JsonSerializerSettings. For example:

Dim jsonSettings As New Newtonsoft.Json.JsonSerializerSettings With {.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.All}
Dim jsonOut As String = Newtonsoft.Json.JsonConvert.SerializeObject(objects, jsonSettings)

The TypeNameHandling = Newtonsoft.Json.TypeNameHandling.All tells JSON to handle the datatypes while relying on the $ for information.

Pang
  • 9,564
  • 146
  • 81
  • 122
firas489
  • 131
  • 5
  • So I have in essence the inverse of this problem? I'm writing a tool to create json schema, and need to output $schema, $id, #ref and the like. I'm struggling with a good way to approach that, the current thought is to potentially have something that runs post that will replace 'id' with '$id' but feels kludgy. Happy to place this in a new question if need be. – Jeff Patton Nov 30 '20 at 18:07