How do C# classes deal with dollar signs in JSON?

橙三吉。 提交于 2019-11-27 03:54:51

问题


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 no allowed by the language. I'm using JSON.NET from Newtonsoft to convert JSON to C# objects. How can I get around this problem?


回答1:


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

[JsonProperty(PropertyName = "$someName")]
public string SomeName { get; set; }



回答2:


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



回答3:


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 meta data, 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.

Hope that helps..



来源:https://stackoverflow.com/questions/4638585/how-do-c-sharp-classes-deal-with-dollar-signs-in-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!