0

I’m targeting .net framework 4.7 with a winforms application. I started by following this article https://learn.microsoft.com/en-us/dotnet/csharp/tutorials/console-webapiclient so I am using DataContractJsonSerializer. I’m trying to learn about a REST interface that returns JSON -

{"Resource":
    {"@attributes":
        {"name":"Asset",
        "resourceId":"Asset",
        "type":"Resource"
        }
    }
}

I used netwonsoft.json 12.0.2 to paste the JSON as classes. It ignores the ‘@’ character and creates a member “attributes” in class “Resource” with type “Attributes” .
When DataContractJsonSerializer attempts to deserialise the JSON it skips the @attribute element, I presume because it does not match the class name.

Is there a way to map the element @attributes to my attributes member / class?

I have tried adding [DataMember(Name = "@attributes")] on the attributes member of the Resource class and a [DataContract(Name = "@attributes")] on the Attributes class but still the element appears to be skipped (attributes member of Resource is null).

AlecJames
  • 11
  • 4
  • Could you please [edit] post with valid JSON? Also generally Json.Net is the desrializer of choice (and duplicate covers all sorts of way to use it to rename property), if you must use `DataContractJsonSerializer` clarify it in the post - likely will need another duplicate. – Alexei Levenkov Jul 19 '19 at 16:37
  • I don't have to use DataContractJsonSerializer; I'm only using it because it is in the article I followed for creating a REST client. (see edited post) – AlecJames Jul 20 '19 at 09:47

1 Answers1

0

Yes, use JsonProperty

public class MyClass
{
    [JsonProperty("@attributes")]
    public string attributes { get; set; }
}
Equalsk
  • 7,954
  • 2
  • 41
  • 67
  • I think this attribute is just for newtonsoft.json JsonConvert.DeserializeObject. – AlecJames Jul 22 '19 at 14:14
  • @AlecJames Sorry, I must have misunderstood the part in your question mentioning Newtonsoft. – Equalsk Jul 22 '19 at 14:42
  • Its my mistake - I thought that the newtonsoft component added and provided the paste as json classes to the paste special menu because I thought it appeared after I installed it. But the builtin paste as classes appears depending on whether it can paste as classes. – AlecJames Jul 23 '19 at 10:38