Hi i'm newbie in c# dev and i'm not good at english i try to get value from json but it gives error [https://www.tutorialsteacher.com/articles/convert-json-string-to-object-in-csharp]
If anyone can help me with simple code I would be very grateful.
{
"result": [{
"company": "Server",
"results": [{
"name": "Server-01",
"access": ["8.8.8.8:443", "1.1.1.1:443"],
"is_ok": "0"
}, {
"name": "Server-02",
"access": ["8.8.8.8:443", "1.1.1.1:443"],
"is_ok": "0"
}, {
"name": "Server-03",
"access": ["8.8.8.8:443", "1.1.1.1:443"],
"is_ok": "1"
}, {
"name": "Server-04",
"access": ["8.8.8.8:443", "1.1.1.1:443"],
"is_ok": "0"
}, {
"name": "Server-05",
"access": ["8.8.8.8:443", "1.1.1.1:443"],
"is_ok": "0"
}]
}]
}
CodePudding user response:
C# can be different. Like .Net Framework or .Net Core / .Net, so next time please provide which framework do you use.
The are two common ways to deserialize JSON string - Json.NET (3rd party) or System.Text.Json (part of .Net).
For correct deserealization first of all you must provide valid models. But sometimes JSON properties violates C# Naming Conventions or they even can't be represented in code (e.g. property name with whitespace or "is_ok" from your JSON). To avoid this you must to use property attribute that connect your property in code and property in JSON. It's:
[JsonProperty("PropertyName")]
for Json.NET[JsonPropertyName("PropertyName")]
for System.Text.Json
So, summing up the above, you must add models similar to this:
public class ResultWrapper
{
[JsonProperty("result")] //use one of it based on selected library
[JsonPropertyName("result")]
public List<Result> Result { get; set; }
}
public class Result
{
[JsonProperty("company")]
[JsonPropertyName("company")]
public string Company { get; set; }
[JsonProperty("results")]
[JsonPropertyName("results")]
public List<ResultItem> Results { get; set; }
}
public class ResultItem
{
[JsonProperty("name")]
[JsonPropertyName("name")]
public string Name { get; set; }
[JsonProperty("access")]
[JsonPropertyName("access")]
public List<string> Access { get; set; }
[JsonProperty("is_ok")]
[JsonPropertyName("is_ok")]
public string IsOk { get; set; }
}
and use one of next deserealization methods:
//Json.Net
var deserializedJsonNet = JsonConvert.DeserializeObject<ResultWrapper>(jsonFromQuestion);
//System.Text.Json
var deserializedSystemTextJson = JsonSerializer.Deserialize<ResultWrapper>(jsonFromQuestion);