Reputation: 445
So I'm watching the tutorials provided by Microsoft on ASP.Net
They created a class named product which looks like this:
public class Product
{
public string Id { get; set; }
public string Maker { get; set; }
[JsonPropertyName("img")]
public string Image { get; set; }
public string Url { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int[] Ratings { get; set; }
public override string ToString() => JsonSerializer.Serialize<Product>(this);
}
I don't know what this is
[JsonPropertyName("img")]
and I have no idea how to search for it on Google.
I don't understand what those square brackets are (they should define an array, but what's their point in that case?)
Also, what's the point of the whole line? What does it do?
Thanks.
Upvotes: 0
Views: 165
Reputation: 342
In c#, you define arrays like this:
string[] companies = new string[3] {"Google", "Microsoft", "Facebook"}; //3 is the size and it's necessary when defining array without items. (It isn't necessary now)
So unlike python or javascript, array items are not located inside square brackets.
But there is another thing called an attribute.
Attributes are special classes that inherit from the Attribute
class and you use the constructor of that class in square brackets before the property or method or variable that you want the attribute to apply to it.
In this example, You apply the JsonPropertyName
attribute to the Image
as the following:
[JsonPropertyName("img")]
public string Image { get; set; }
The JsonSerializer.Serialize<Product>(this)
will check each property's attribute (if it has one) and applies that attribute while serializing. When you Serialize an instance of this class using the overridden ToString()
method, this attribute forces the serializer to use img for JSON property name instead of Image so you will get img instead of Image in JSON.
Example without using attribute:
{
"Id": <Id>,
"Maker": <Maker>,
"Image": <Image>, //Image
"Url": <Url>,
"Title": <Title>,
"Description": <Description>,
"Ratings": [<Ratings>]
}
But when you use [JsonPropertyName("img")]
attribute, it will look like this:
{
"Id": <Id>,
"Maker": <Maker>,
"img": <Image>, //img
"Url": <Url>,
"Title": <Title>,
"Description": <Description>,
"Ratings": [<Ratings>]
}
For more information about this attribute you can refer to following links:
usage and
structure
And for more information about attributes, visit this.
Upvotes: 3
Reputation: 31
It describes and gives some features for one bottom property. You can search it as "Attributes in C#". You will get a lot of documentation for them.
Upvotes: 3