Building a C # Object for JSON

I am trying to create C # objects for a JSON response in my application. I have JSON as shown below

{ "@odata.context": "https://example.com/odata/$metadata#REQ", "value": [ { "Id": 17, "Name": "Req" } ] } 

I am not sure how to create a C # object for @odata.context

 public class RootObject { public string @odata.context { get; set; } public List<Value> value { get; set; } } 

It throws an error in @ odata.context

+5
source share
2 answers

This is because identifiers in C # cannot have the @ sign. You did not specify which library you are using, but if it is JSON.NET , you can simply decorate the properties.

 public class Root { [JsonProperty("@odata.context")] public string OdataContext { get; set; } [JsonProperty("value")] public List<Value> Value { get; set; } } public class Value { [JsonProperty("Id")] public long Id { get; set; } [JsonProperty("Name")] public string Name { get; set; } } 
+6
source

I would recommend using Newtonsoft Json.NET .

On the documentation page you can also find tons of samples. This is exactly the solution to your problem (I added the problem field "odata.context" so that you can understand how to match the JSON response and your class:

https://www.newtonsoft.com/json/help/html/DeserializeObject.htm

 public class Account { [JsonProperty("@odata.context")] public string myText { get; set; } public bool Active { get; set; } public DateTime CreatedDate { get; set; } public IList<string> Roles { get; set; } } string json = @"{ '@odata.context': 'this is an attribute with an @ in the name.', 'Active': true, 'CreatedDate': '2013-01-20T00:00:00Z', 'Roles': [ 'User', 'Admin' ] }"; Account account = JsonConvert.DeserializeObject<Account>(json); Console.WriteLine(account.myText); // this is an attribute with an @ in the name. 

Prevent the use of "@" for your governors. Use JsonProperty . This allows you to map JsonProperty to one of the fields in your class (in this case, it maps the JSON @ odata.context property to the myText property of your class.

0
source

Source: https://habr.com/ru/post/1272746/


All Articles