Lord Vermillion
Lord Vermillion

Reputation: 5424

Deserialize JSON with '@' in attribute name

I have a JSON-object that contains an attribute named @id:

{"@id": "231"}

In my object i tried both:

[DataMember(Name = "@id")]
public string id { get; set; }

and

public string @id { get; set; }

but when i deserialize with json.net the id always gets null:

JsonConvert.DeserializeObject<TestObc>(jsonString);

How can i deserialize the @id attribute?

Upvotes: 0

Views: 932

Answers (2)

Evk
Evk

Reputation: 101453

Changing DataMember to JsonProperty helps indeed, but if you still want to use DataMember - just decorate your class itself with DataContract attribute (that is what you probably forgot to do):

[DataContract]
class YourClass {
    [DataMember(Name = "@id")]
    public string id { get; set; }
}

Upvotes: 2

Amit Kumar Ghosh
Amit Kumar Ghosh

Reputation: 3726

try like this -

class Root{
   [JsonProperty("@id")]
   public string id { get; set; }
}

Test -

var json = "{'@id': '231'}";
var t = JsonConvert.DeserializeObject<Root>(json);
Console.WriteLine(t.id); //231

Upvotes: 3

Related Questions