Home > Enterprise >  Deserialize json where an attribute has the same name as a built in datatype, in C#
Deserialize json where an attribute has the same name as a built in datatype, in C#

Time:11-05

I faced a problem that I could not find any solution to by google...

   JavaScriptSerializer js = new JavaScriptSerializer();
   MyClass myObject = js.Deserialize<MyClass>(jsonstring); 

What about if an attribute in the json data is called "short"? I cannot make a class like this:

public class MyClass
{
   public int A;        
   public int B;       
   public int short;
}

So how can I get the jsonstring into an object in an easy way? Very thankful for all help I can get.

CodePudding user response:

You can use @ in

public class MyClass
{
   public int A;        
   public int B;       
   public int @short;
}

CodePudding user response:

short is a keyword (documentation; you will need to call the variable something else. Short would work just fine since keywords are case sensitive, and all keywords are lowercase.

In @Balastrong's answer:

public class MyClass
{
   public int A;        
   public int B;       
   public int @short;
}

The @ symbol is being used as a "verbatim identifier" (documentation; see number 1). This allows the interpreter to understand @short as the identifier short instead of the keyword short.

Hope this cleared some things up.

  • Related