Reputation: 375
m trying to deserialize a Json file, using this class as a model:
using CsQuery.StringScanner.Patterns;
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.Text;
namespace Test_Api
{
public class Metric
{
public string __name__ { get; set; }
public string instance { get; set; }
public string job { get; set; }
}
public class Result
{
public Metric metric { get; set; }
public IList<Lucene.Net.Support.Number> value { get; set; }
}
public class Data
{
public string resultType { get; set; }
public IList<Result> result { get; set; }
}
public class Application
{
public string status { get; set; }
public Data data { get; set; }
}
}
my Program.cs is:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using QuickType;
namespace Test_Api
{
class Program
{
static async System.Threading.Tasks.Task Main(string[] args)
{
List<Application> DataG = new List<Application>();
using (var httpClient = new HttpClient())
{
using (var response = await httpClient.GetAsync("http://localhost:9090/api/v1/query?query=go_memstats_gc_cpu_fraction"))
{
string apiResponse = await response.Content.ReadAsStringAsync();
DataG = JsonConvert.DeserializeObject<List<Application>>(apiResponse);
}
}
Console.WriteLine(DataG);
}
}
}
It keeps giving me this error:
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Test_Api.Application]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
I want to know if there is a standart way to deserialize json things using a specific model, any help would be appreciated, be gentel please, Im a newbie.
EDIT: The Json I want to get the values from is:
{
"status": "success",
"data": {
"resultType": "vector",
"result": [
{
"metric": {
"__name__": "process_cpu_seconds_total",
"instance": "localhost:9090",
"job": "prometheus"
},
"value": [
1545222126.353,
"0.615464"
]
}
]
}
}
Upvotes: 2
Views: 1733
Reputation: 18153
You would need to use
var result = JsonConvert.DeserializeObject<Application>(apiResponse);
Your Json returns a single instance of the Application
, while you were attempting to deserialize the Json as a List<Application>
as per the code in OP. This was the cause of error.
Upvotes: 1
Reputation: 134
You need to convert your response to array first
Application[] result = JsonConvert.DeserializeObject<Application[]>(apiResponse,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
and then you can create list from array i.e
List<Application> DataG = new List<Application>();
for(int i = 0; i < result.Length; i++)
{
DataG.Add(result[i]);
}
now you can use your list
Upvotes: 0