JSON to object C# (mapping complex API response to C# object) - c#

I am able to handle simple JSON serialization and deserialization but this API response seems little complicated, and I am seeking an advice as to what would be ideal approach to tackle this.
I'm trying to call an API for MVC application.
Goal is to map API data to model.
API endpoint is
https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=1min&apikey=MyAPIKey
Troubles here are:
JSON data keys have white space in them.
When I tried doing paste special in Visual studio, It gave me a long
list of classes for each date entry separately, because this API
call returns a separate set of information for date.
To solve problem explained in point 1, I used [JsonProperty("1. Information")] in class. And in my code..
public async Task TSI()
{
HttpClient client = new HttpClient();
//Uri uri = new Uri("http://date.jsontest.com/");
Uri uri = new Uri("https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=5min&apikey=demo");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
dynamic result = await response.Content.ReadAsAsync<object>();
IEnumerable<dynamic> dObj = JsonConvert.DeserializeObject<dynamic>(result.ToString());
IEnumerable<dynamic> t1 = dObj.FirstOrDefault();
IEnumerable<dynamic> t2 = dObj.LastOrDefault();
dynamic MetaData = t1.FirstOrDefault();
Rootobject ro = new Rootobject();
ro.MetaData = MetaData;
}
PS: I'm relatively new to make API calls and handling them.
I was able to make a call to
date.jsontest.com
and map the API data to model (which I had created using paste special)
//API response
{
"time": "12:53:22 PM",
"milliseconds_since_epoch": 1504875202754,
"date": "09-08-2017"
}
//C# code to map to API data
public class sampleObject
{
public string time { get; set; }
public long milliseconds_since_epoch { get; set; }
public string date { get; set; }
}
My RootObject looks like this:
public class Rootobject
{
[JsonProperty("Meta Data")]
public MetaData MetaData { get; set; }
[JsonProperty("Time Series (1min)")]
public TimeSeries1Min TimeSeries1min { get; set; }
}
public class MetaData
{
[JsonProperty("1. Information")]
public string _1Information { get; set; }
[JsonProperty("2. Symbol")]
public string _2Symbol { get; set; }
[JsonProperty("3. Last Refreshed")]
public string _3LastRefreshed { get; set; }
[JsonProperty("4. Interval")]
public string _4Interval { get; set; }
[JsonProperty("5. Output Size")]
public string _5OutputSize { get; set; }
[JsonProperty("6. Time Zone")]
public string _6TimeZone { get; set; }
}
// I have so many of these sub-classes for dates, which again is an issue
public class TimeSeries1Min
{
public _20170907160000 _20170907160000 { get; set; }
public _20170907155900 _20170907155900 { get; set; }
....
....}
public class _20170907160000
{
public string _1open { get; set; }
public string _2high { get; set; }
public string _3low { get; set; }
public string _4close { get; set; }
public string _5volume { get; set; }
}
public class _20170907155900
{
public string _1open { get; set; }
public string _2high { get; set; }
public string _3low { get; set; }
public string _4close { get; set; }
public string _5volume { get; set; }
}

It is hard to create a model from this json, but you can convert those data to dictionary
var jObj = JObject.Parse(json);
var metadata = jObj["Meta Data"].ToObject<Dictionary<string, string>>();
var timeseries = jObj["Time Series (1min)"].ToObject<Dictionary<string, Dictionary<string, string>>>();

The following code should do what you want
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsStringAsync();
var obj = JsonConvert.DeserializeObject<Rootobject>(result);
//No idea what you want to do with this line as there is no MetaData property on the root object
obj.MetaData = MetaData;
}

Related

How to deserialize json object with no parent class?

I'm trying and failing to write a program that will make an API call and then turn the returned items into objects that fit my model. Specifically I can't make it deserealize, and I suspect it has something to do with how the json is return compared to what my model looks like.
The data I'm trying to get looks like this;
https://api.nasa.gov/planetary/apod?start_date=2022-03-01&end_date=2022-03-08&api_key=DEMO_KEY
As you can see, it consists of an array of items, but there is no name for the array items. When I paste this into the Get-model with Paste JSON as Classes, I get this;
public class GetApodItemsResult
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public string copyright { get; set; }
public string date { get; set; }
public string explanation { get; set; }
public string hdurl { get; set; }
public string media_type { get; set; }
public string service_version { get; set; }
public string title { get; set; }
public string url { get; set; }
}
My entire code works just fine up until I need to serialize the JSON with this line:
var responseObject = await response.Content.ReadFromJsonAsync<GetApodItemsResult>();
, where I get this message;
System.Text.Json.JsonException: 'The JSON value could not be converted to UnnamedSpaceProject.Models.GetApodItemsResult.
Interestingly I know that the code works on a spotify api call, so the code really should work largely the same, which leads me to believe that the problem is with how the JSON is formatted.
How do I get around that? Because I don't see a way to have the root object contain an unnamed array.
Your GetApodItemsResult class is not a valid class to deserialize the content you get from server, the correct deserialization type will be List<Class1> or Class1[]
var responseObject = await response.Content.ReadFromJsonAsync<List<Class1>>();
I recommend you to use more meaningful name instead of Class1 you can name it Apod (acronym for Astronomy Picture of the Day)
Full working code:
using System.Text.Json;
using System.Text.Json.Serialization;
HttpClient client = new HttpClient();
const string BaseUrl = #"https://api.nasa.gov/";
var response = await client.GetAsync($"{BaseUrl}planetary/apod?start_date=2022-03-01&end_date=2022-03-08&api_key=DEMO_KEY");
if ((response.StatusCode != System.Net.HttpStatusCode.OK))
{
Console.Error.WriteLine("field to fetch data from server");
}
var responseBody = await response.Content.ReadAsStringAsync();
var pictuersList = JsonSerializer.Deserialize<List<Apod>>(responseBody);
Console.WriteLine($"there is {pictuersList?.Count} apod downloaded successflly");
Console.WriteLine("done");
public class Apod
{
[JsonPropertyName("copyright")]
public string Copyright { get; set; } = "";
[JsonPropertyName("date")]
public string Date { get; set; } = "";
[JsonPropertyName("explanation")]
public string Explanation { get; set; } = "";
[JsonPropertyName("hdurl")]
public string Hdurl { get; set; } = "";
[JsonPropertyName("media_type")]
public string MediaType { get; set; } = "";
[JsonPropertyName("service_version")]
public string ServiceVersion { get; set; } = "";
[JsonPropertyName("title")]
public string Title { get; set; } = "";
[JsonPropertyName("url")]
public string Url { get; set; } = "";
}
The object your JSON containing is not some container with the array in it, it IS the array. So, the correct code would be like this:
var responseObject = await response.Content.ReadFromJsonAsync<Class1[]>();
The correct JSON for your code would look like this:
{
"Property1": [{
"copyright": "Jeff DaiTWAN",
"date": "2022-03-01",
"url": "https://apod.nasa.gov/apod/image/2203/DuelingBands_Dai_960.jpg"
}]
}

How to convert JArray to generic List<>

Via an http Post, I send html FormData to my Web Api2 controller.
The FormData contains one or more images, as well as client properties.
My front end Angular 5 service sends the http post (working fine):
var url = this.host + 'import/MediaUpload';
return this.http.post(url, formData, options)
.map((result: any) => result._body)
.catch(this.handleError);
I would like to convert the FormData to a generic List of MediaInfo class (defined below this MediaUpload() method) :
public async Task<HttpResponseMessage> MediaUpload(int projectId, int sectionId)
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var provider = await Request.Content.ReadAsMultipartAsync<InMemoryMultipartFormDataStreamProvider>(new InMemoryMultipartFormDataStreamProvider());
//access form data
NameValueCollection formData = provider.FormData;
List<MediaInfo> listMedia = new List<MediaInfo>();
//dynamic jsonData = JObject.Parse(formData["MediaInfo"]); // THROWS ERROR
JArray ary = JArray.Parse(formData["MediaInfo"]);
foreach (var item in ary) {
//listMedia.Add((MediaInfo)item); // ???
Console.WriteLine(item);
}
//access files
IList<HttpContent> files = provider.Files;
HttpContent file1 = files[0];
var thisFileName = file1.Headers.ContentDisposition.FileName.Trim('\"');
// additional file upload code removed, working fine..
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Headers.Add("DocsUrl", URL);
return response;
}
public class MediaInfo
{
public string PatientID { get; set; }
public string PatientFirstName { get; set; }
public string PatientLastName { get; set; }
public string PatientUID { get; set; }
public string PatientDOB { get; set; }
public string ExamDate { get; set; }
public string ExamDevice { get; set; }
public string SerialNo { get; set; }
public string Eye { get; set; }
public int DeviceID { get; set; }
public int CSIInstanceID { get; set; }
public int MediaNo { get; set; }
public string Procedure { get; set; }
public string FileName { get; set; }
public int FileSize { get; set; }
}
I thought I could do something like :
listMedia.Add((MediaInfo)item;
But I'm missing the correct conversion somewhere.
You can convert a JObject to a type of your choosing with the .ToObject<T>() method.
https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Linq_JToken_ToObject__1_1.htm
In this case you want your code to look like this:
listMedia.Add(item.ToObject<MediaInfo>());
You could also use JsonConvert.DeserializeObject to convert it directly into the desired type provided formData["MediaInfo"] returned well formed JSON.
List<MediaInfo> listMedia = JsonConvert.DeserializeObject<List<MediaInfo>>(formData["MediaInfo"]);

get deserialize json objects into list c#

I'm getting json string from webapi like this
{"page":1,"total_results":33,"total_pages":2,"results":
[{"vote_count":8017,"id":603,"video":false,"vote_average":7.9,"title":"The Matrix","popularity":7.82272,"poster_path":"\/lZpWprJqbIFpEV5uoHfoK0KCnTW.jpg","original_language":"en","original_title":"The Matrix","genre_ids":[28,878],"backdrop_path":"\/7u3pxc0K1wx32IleAkLv78MKgrw.jpg","adult":false,"overview":"Set in the 22nd century, The Matrix tells the story of a computer hacker who joins a group of underground insurgents fighting the vast and powerful computers who now rule the earth.","release_date":"1999-03-30"},
{"vote_count":2750,"id":605,"video":false,"vote_average":6.4,"title":"The Matrix Revolutions","popularity":5.073697,"poster_path":"\/sKogjhfs5q3azmpW7DFKKAeLEG8.jpg","original_language":"en","original_title":"The Matrix Revolutions","genre_ids":[12,28,53,878],"backdrop_path":"\/pdVHUsb2eEz9ALNTr6wfRJe5xVa.jpg","adult":false,"overview":"The human city of Zion defends itself against the massive invasion of the machines as Neo fights to end the war at another front while also opposing the rogue Agent Smith.","release_date":"2003-11-05"},
{"vote_count":0,"id":411948,"video":false,"vote_average":0,"title":"Matrix","popularity":1.004394,"poster_path":"\/cseRq8R9RGN66SNUgcD7RJAxBI7.jpg","original_language":"en","original_title":"Matrix","genre_ids":[],"backdrop_path":null,"adult":false,"overview":"John Whitney, Sr. (April 8, 1917 – September 22, 1995) was an American animator, composer and inventor, widely considered to be one of the fathers of computer animation.","release_date":"1971-05-18"}]}
I only want to get title from above string into list.
Here's my code
public List<string> ExtractMoviesList(string movieTitle)
{
using (var client = new HttpClient())
{
// HTTP GET
var response = client.GetAsync(string.Format("{0}{1}", movies_Url, movieTitle)).Result;
using (HttpContent content = response.Content)
{
var json = content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<Movies>>(json.Result);
return result.Select(p=>p.Title).ToList();
}
}
}
There's something wrong with this line of code: var result = JsonConvert.DeserializeObject<List<Movies>>(json.Result); after this line executed the var result is getting just null.
Your problem is that you are trying to deserialize your JSON as a List<T>, but the root object in your JSON is not an array, it's an object. This is easy to see if you format and indent your JSON using, say, https://jsonformatter.curiousconcept.com/:
{
"page":1,
"total_results":33,
"total_pages":2,
"results":[
{
"title":"The Matrix",
// Other fields
},
// Other movies
]
}
The data model to which you are binding your JSON must reflect this outer container object for deserialization to succeed. Luckily http://json2csharp.com/ or Paste JSON as Classes will generate one for you:
public class Movie
{
public string title { get; set; }
public int vote_count { get; set; }
public int id { get; set; }
public bool video { get; set; }
public double vote_average { get; set; }
public double popularity { get; set; }
public string poster_path { get; set; }
public string original_language { get; set; }
public string original_title { get; set; }
public List<object> genre_ids { get; set; }
public string backdrop_path { get; set; }
public bool adult { get; set; }
public string overview { get; set; }
public string release_date { get; set; }
}
public class RootObject
{
public int page { get; set; }
public int total_results { get; set; }
public int total_pages { get; set; }
public List<Movie> results { get; set; }
}
Now you can do:
var result = JsonConvert.DeserializeObject<RootObject>(json.Result);
return result.results.Select(m => m.title).ToList();
Incidentally, if you don't want to create a data model just to extract the titles from this JSON, you can use Json.NET's LINQ to JSON functionality to load and query the JSON directly:
var result = JToken.Parse(json.Result);
return result.SelectTokens("results[*].title").Select(t => (string)t).ToList();
Here I am using SelectTokens() with the JsonPATH wildcard operator [*] to find all entries in the results array.
Working .Net fiddle showing both options.

preview JSON on DataGridView

I have an ASP MVC Web Api that returns these data as Json :
"[{\"OpID\":15,\"DeviceID\":1,\"DeviceType\":\"LED1\",\"DeviceState\":true,\"TurnOnTime\":\"2016-07-26T21:10:05.607\",\"TurnOffTime\":null,\"ToggleTime\":\"2016-07-26T21:10:05.61\",\"ToggleHour\":null},{\"OpID\":16,\"DeviceID\":5,\"DeviceType\":\"TV\",\"DeviceState\":true,\"TurnOnTime\":\"2016-07-26T21:10:09.283\",\"TurnOffTime\":null,\"ToggleTime\":\"2016-07-26T21:10:09.283\",\"ToggleHour\":null}]"
I`m trying to deserialize it using this code :
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://engeek.azurewebsites.net/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("api/operation").Result;
string str = await response.Content.ReadAsStringAsync();
List<operation> myDeserializedObjList = (List<operation>)JsonConvert.DeserializeObject(str , typeof(List<operation>));
dataGridView1.DataSource = myDeserializedObjList;
and here is my model:
class operation
{
[JsonProperty("OpID")]
public int OpID { get; set; }
[JsonProperty("DeviceID")]
public Nullable<int> DeviceID { get; set; }
[JsonProperty("DeviceType")]
public string DeviceType { get; set; }
[JsonProperty("DeviceState")]
public Nullable<bool> DeviceState { get; set; }
[JsonProperty("TurnOnTime")]
public Nullable<System.DateTime> TurnOnTime { get; set; }
[JsonProperty("TurnOffTime")]
public Nullable<System.DateTime> TurnOffTime { get; set; }
[JsonProperty("ToggleTime")]
public Nullable<System.DateTime> ToggleTime { get; set; }
[JsonProperty("ToggleHour")]
public Nullable<int> ToggleHour { get; set; }
}
and the serialization code :
public string Getoperation()
{
var data = new List<operation>();
data = db.operations.ToList();
string str = JsonConvert.SerializeObject(data, Formatting.None);
return str;
}
It gives me :
couldn`t convert or cast from string to List
What should I do ?
Somewhere in the MVC code where you are creating the JSON response, you are serializing the List<operation> as a JSON string, and then serializing that JSON string again.
Show the code where you serialize the List<operation> (that part looks good, thanks!) and the code where you return that JSON string to the client, and I'll probably be able to show you where that's happening.
You have a slight variation on the same problem this other guy had yesterday, except he only double-encoded one branch of his object, while you double-encoded the entire thing.

Deserialize nested JSON Response with RestSharp Client

I'd like to consume a REST Api and deserialize the nested JSON Response. For that purpose I tried to create some POCO classes which represent the JSON Response [1].
The response looks like this:
{
"success": true,
"message": "OK",
"types":
[
{
"name": "A5EF3-ASR",
"title": "ITIL Foundation Plus Cloud Introduction",
"classroomDeliveryMethod": "Self-paced Virtual Class",
"descriptions": {
"EN": {
"description": "some Text null",
"overview": null,
"abstract": "Some other text",
"prerequisits": null,
"objective": null,
"topic": null
}
},
"lastModified": "2014-10-08T08:37:43Z",
"created": "2014-04-28T11:23:12Z"
},
{
"name": "A4DT3-ASR",
"title": "ITIL Foundation eLearning Course + Exam",
"classroomDeliveryMethod": "Self-paced Virtual Class",
"descriptions": {
"EN": {
"description": "some Text"
(...)
So I created the following POCO classes:
public class Course
{
public bool success { get; set; }
public string Message { get; set; }
public List<CourseTypeContainer> Type { get; set; }
}
/* each Course has n CourseTypes */
public class CourseType
{
public string Name { get; set; }
public string Title { get; set; }
public List<CourseTypeDescriptionContainer> Descriptions { get; set; }
public DateTime LastModified { get; set; }
public DateTime Created { get; set; }
}
public class CourseTypeContainer
{
public CourseType CourseType { get; set; }
}
/* each CourseType has n CourseTypeDescriptions */
public class CourseTypeDescription
{
public string Description { get; set; }
public string Overview { get; set; }
public string Abstract { get; set; }
public string Prerequisits { get; set; }
public string Objective { get; set; }
public string Topic { get; set; }
}
public class CourseTypeDescriptionContainer
{
public CourseTypeDescription CourseTypeDescription { get; set; }
}
And this is the API Code:
var client = new RestClient("https://www.someurl.com");
client.Authenticator = new HttpBasicAuthenticator("user", "password");
var request = new RestRequest();
request.Resource = "api/v1.0/types";
request.Method = Method.GET;
request.RequestFormat = DataFormat.Json;
var response = client.Execute<Course>(request);
EDIT 1: I found a Typo, the Type property in AvnetCourse should be named Types:
public List<AvnetCourseTypeContainer> Type { get; set; } // wrong
public List<AvnetCourseTypeContainer> Types { get; set; } // correct
Now the return values look like:
response.Data.success = true // CORRECT
repsonse.Data.Message = "OK" // CORRECT
response.Data.Types = (Count: 1234); // CORRECT
response.Data.Types[0].AvnetCourseType = null; // NOT CORRECT
EDIT 2: I implemented the Course.Types Property using a List<CourseType> instead of a List<CourseTypeContainer>, as proposed by Jaanus. The same goes for the CourseTypeDescriptionContainer:
public List<CourseTypeContainer> Type { get; set; } // OLD
public List<CourseTypeDescriptionContainer> Descriptions { get; set; } // OLD
public List<CourseType> Type { get; set; } // NEW
public List<CourseTypeDescription> Descriptions { get; set; } // NEW
Now the response.Data.Types finally are properly filled. However, the response.Data.Types.Descriptions are still not properly filled, since there is an additional language layer (e.g. "EN"). How can I solve this, without creating a PACO for each language?
EDIT 3: I had to add an additional CourseTypeDescriptionDetails class, where I would store the descriptive Data. In my CourseTypeDescription I added a property of the Type List for each language. Code Snippet:
public class AvnetCourseType
{
public List<CourseTypeDescription> Descriptions { get; set; }
// other properties
}
public class CourseTypeDescription
{
public List<CourseTypeDescriptionDetails> EN { get; set; } // English
public List<CourseTypeDescriptionDetails> NL { get; set; } // Dutch
}
public class CourseTypeDescriptionDetails
{
public string Description { get; set; }
public string Overview { get; set; }
public string Abstract { get; set; }
public string Prerequisits { get; set; }
public string Objective { get; set; }
public string Topic { get; set; }
}
It works now, but I need to add another property to CourseTypeDescription for each language.
OLD: The return values are
response.Data.success = true // CORRECT
repsonse.Data.Message = "OK" // CORRECT
response.Data.Type = null; // WHY?
So why does my response.Type equal null? What am I doing wrong?
Thank you
Resources:
[1] RestSharp Deserialization with JSON Array
Try using this as POCO:
public class Course
{
public bool success { get; set; }
public string message { get; set; }
public List<CourseTypeContainer> Types { get; set; }
}
Now you have list of CourseTypeContainer.
And CourseTypeContainer is
public class CourseTypeContainer
{
public CourseType CourseType { get; set; }
}
So when you are trying to get response.Data.Types[0].AvnetCourseType , then you need to have field AvnetCourseType inside CourseTypeContainer
Or I think what you want is actually this public List<CourseType> Types { get; set; }, you don't need a container there.
Just in case this helps someone else, I tried everything here and it still didn't work on the current version of RestSharp (106.6.2). RestSharp was completely ignoring the RootElement property as far as I could tell, even though it was at the top level. My workaround was to manually tell it to pull the nested JSON and then convert that. I used JSON.Net to accomplish this.
var response = restClient.Execute<T>(restRequest);
response.Content = JObject.Parse(response.Content)[restRequest.RootElement].ToString();
return new JsonDeserializer().Deserialize<T>(response);
I used http://json2csharp.com/ to create C# classes from JSON.
Then, renamed RootObject to the ClassName of the model file I'm creating
All the data in the nested json was accessible after RestSharp Deserializitaion similar to responseBody.data.Subject.Alias
where data, Subject and Alias are nested nodes inside the response JSON received.

Categories