Reputation: 37
I am using Newtonsoft for JSON string to deserialize object but I could not get value for default attribute/properties
{
"displayName": "Token",
"name": "token",
"type": "string",
"default": ""
}
C# code
public class ItemProperties
{
public string displayName { get; set; }
public string name { get; set; }
public string type { get; set; }
[JsonPropertyName("default")]
public dynamic defaultValue{ get; set; }
}
Upvotes: 1
Views: 177
Reputation: 1502036
You're using JsonPropertyNameAttribute
which is part of System.Text.Json
. As you're using Json.NET (Newtonsoft.Json) you need JsonPropertyAttribute
instead. I would actually apply it to all the properties, and then rename them to be have idiomatic C# names. Here's a complete example:
using Newtonsoft.Json;
using System;
using System.IO;
public class ItemProperties
{
[JsonProperty("displayName")]
public string DisplayName { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("default")]
public dynamic DefaultValue { get; set; }
}
class Program
{
static void Main()
{
string json = File.ReadAllText("test.json");
var properties = JsonConvert.DeserializeObject<ItemProperties>(json);
Console.WriteLine($"DisplayName: {properties.DisplayName}");
Console.WriteLine($"Name: {properties.Name}");
Console.WriteLine($"Type: {properties.Type}");
Console.WriteLine($"DefaultValue: {properties.DefaultValue}");
}
}
Sample JSON:
{
"displayName": "x",
"name": "y",
"type": "z",
"default": 10
}
Output:
DisplayName: x
Name: y
Type: z
DefaultValue: 10
Upvotes: 3
Reputation: 37
I found my answer it should be accessible using You can use keywords in C# as identifiers by prepending @
in front of them
C# code
public class ItemProperties
{
public string displayName { get; set; }
public string name { get; set; }
public string type { get; set; }
public dynamic @default { get; set; }
}
then you can access like objItem.@default
.
Upvotes: 0