I need to parse JSON to an object which includes list of objects. So there`s my JSON.
I created two classes for it. There are them
public class Picture
{
public int id { get; set; }
public string pageURL { get; set; }
public string type { get; set; }
public string tags { get; set; }
public string previewURL { get; set; }
public int previewWidth { get; set; }
public int previewHeight { get; set; }
public string webformatURL { get; set; }
public int webformatWidth { get; set; }
public int webformatHeight { get; set; }
public string largeImageURL { get; set; }
public int imageWidth { get; set; }
public int imageHeight { get; set; }
public int imageSize { get; set; }
public int views { get; set; }
public int downloads { get; set; }
public int favorites { get; set; }
public int likes { get; set; }
public int comments { get; set; }
public int user_id { get; set; }
public string user { get; set; }
public string userImageURL { get; set; }
}
public class PicturesByTopic
{
public int total { get; set; }
public int totalHits { get; set; }
public List<Picture> Pictures { get; set; }
public PicturesByTopic()
{
Pictures = new List<Picture>();
}
}
I tried to parse them in two ways:
static PicturesByTopic GetPicturesByTopic(Message message)
{
var topic = message.Text;
var url = $"https://pixabay.com/api/?key={PicturesAPIKEY}&q={topic}&image_type=photo&pretty=true";
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
string response;
using (StreamReader stream = new StreamReader(httpWebResponse.GetResponseStream()))
{
response = stream.ReadToEnd();
}
PicturesByTopic picturesByTopic = JsonConvert.DeserializeObject<PicturesByTopic>(response);
return picturesByTopic;
}
And the second variant:
static List<PicturesByTopic> GetPicturesByTopic(Message message)
{
var topic = message.Text;
var url = $"https://pixabay.com/api/?key={PicturesAPIKEY}&q={topic}&image_type=photo&pretty=true";
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
string response;
using (StreamReader stream = new StreamReader(httpWebResponse.GetResponseStream()))
{
response = stream.ReadToEnd();
}
var wrappedText = @"{ ""Prop"": " + response + " }";
var jsonData = JObject.Parse(response);
List<PicturesByTopic> RetsProperties = new List<PicturesByTopic>();
foreach (var prop in jsonData["Prop"])
{
RetsProperties.Add(new PicturesByTopic
{
total = JsonConvert.DeserializeObject<int>(prop.First.ToString()),
totalHits = JsonConvert.DeserializeObject<int>(prop.First.ToString()),
Pictures = JsonConvert.DeserializeObject<Picture[]>(prop.First.ToString())
});
};
return RetsProperties;
}
But I can`t take correct parsing object by two of them. So any thoughts about this? Hope, my explanations was clear enough.