How to convert Json object with ref attribute into c# class?

I have below json object to convert for c# class.

{
   "Token": “Token”,
   "ref": 1 
}

The converted c# class is given below.

public class ABC
{
public string Token{get;set;}
public int ref{get;set;}
}

But I received following error message from c#.

Member modifier ‘ref’ must precede the member type and name

How do I convert JSON into c# class correctly with ref attribute?

Thanks in advance.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

In Newtonsoft.Json, you could do this:

public class ABC
{
    public string Token{get;set;}
    [JsonProperty("ref")]
    public int Ref{get;set;}
}

If you don’t want to do that or can’t do that, use this:

public class ABC
{
    public string Token { get; set; }
    public int @ref {get; set; }
}

Since ref is a C# keyword, you can add the @ symbol which allows you to use it as a property name.

var thing = new ABC { @ref = 0 };
<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d1a5b9b8bfb6ff91a3b4b7">[email protected]</a> = 5;

Your models will serialize as if it were defined as ref.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x