Use the JsonProperty
attribute to indicate the name in the JSON. e.g.
[JsonProperty(PropertyName = "binding type")]
public string BindingType { get; set; }
Question
I'm writing a tool to read JSON files. I'm using the NewtonSoft tool to deserialize the JSOn to a C# class. Here's an example fragment:
"name": "Fubar",
".NET version": "4.0",
"binding type": "HTTP",
The field names contain spaces and other characters (the .) that are invalid in C# identifiers. What is the correct way to do this?
(Unfortunately I don't have the option of changing the JSON format.)
Solution
Use the JsonProperty
attribute to indicate the name in the JSON. e.g.
[JsonProperty(PropertyName = "binding type")]
public string BindingType { get; set; }
OTHER TIPS
If you're using System.Text.Json
, the equivalent attribute is JsonPropertyName
:
[JsonPropertyName(".net version")]
public string DotNetVersion { get; set; }
Example below:
public class Data
{
public string Name { get; set; }
[JsonPropertyName(".net version")]
public string DotNetVersion { get; set; }
[JsonPropertyName("binding type")]
public string BindingType { get; set; }
}
// to deserialize
var data = JsonSerializer.Deserialize<Data>(json);
Not sure why but this did not work for me. In this example I simply return a null for "BindingType" every time. I actually found it much easier to just download the Json result as a string and then do something like:
myString = myString.Replace(@"binding type", "BindingType")
You would do this as the step before deserializing.
Also was less text by a tad. While this worked in my example there will be situations where it may not. For instance if "binding type" was not only a field name but also a piece of data, this method would change it as well as the field name which may not be desirable.
If you want to initialize the Json manually, you can do:
var jsonString = "{" +
"'name': 'Fubar'," +
"'.NET version': '4.0'," +
"'binding type': 'HTTP'," +
"}";
var json = JsonConvert.DeserializeObject(jsonString);
return Ok(json);
Don't forget to include using Newtonsoft.Json;