deserialize json array of object c# RIOT API [NOT WORKING] - json

i've recently started to start on a new small project, but have come across some issues.. I'm not really sure why it's not working honestly.
public partial class MatchlistDto
{
public List<MatchHistory> matchhistory { get; set; }
}
public partial class MatchHistory
{
[JsonProperty("platformId")]
public string platformId { get; set; }
[JsonProperty("gameId")]
public long gameId { get; set; }
[JsonProperty("champion")]
public int champion { get; set; }
[JsonProperty("queue")]
public int queue { get; set; }
[JsonProperty("season")]
public int season { get; set; }
[JsonProperty("timestamp")]
public long timestamp { get; set; }
[JsonProperty("role")]
public string role { get; set; }
[JsonProperty("lane")]
public string lane { get; set; }
}
public partial class SummonerV4
{
public string id { get; set; }
public string accountId { get; set; }
public string puuid { get; set; }
public string profileIconId { get; set; }
public string revisionDate { get; set; }
public string summonerLevel { get; set; }
}
Code from Controller.
[HttpPost]
public async Task<ActionResult> DisplayAccount(string Region, string User)
{
string ApiKey = "TottalyAnApiKey";
SummonerV4 UserInfo = new SummonerV4();
using (var client = new HttpClient())
{
HttpResponseMessage Res = await client.GetAsync("https://" + Region + ".api.riotgames.com/lol/summoner/v4/summoners/by-name/"+ User +"?api_key="+ ApiKey);
if (Res.IsSuccessStatusCode)
{
var apiResponse = Res.Content.ReadAsStringAsync().Result; //First part is to get AccountInformation from user. e.g AccountID.
UserInfo = JsonConvert.DeserializeObject<SummonerV4>(apiResponse);
HttpResponseMessage Res2 = await client.GetAsync("https://" + Region + ".api.riotgames.com" + "/lol/match/v4/matchlists/by-account/" + User + "?api_key=" + ApiKey); //Second part is to collect the Match History from user.
if (Res2.IsSuccessStatusCode)
{
var PersonalResponse2 = Res2.Content.ReadAsStringAsync().Result;
List<MatchlistDto> matchHistoryList = JsonConvert.DeserializeObject<List<MatchlistDto>>(PersonalResponse2);
}
}
}
return View(UserInfo);
}
So whats going on is that, i do get the correct response from RiotGames API but i can't really deserialize it correctly. Please check images. My wish is to store the data in a list or array.
Here you can see all the objects from the response
And here the error

A couple problems:
1: MatchlistDto matchhistory field is misnamed
It should look like this:
public partial class MatchlistDto
{
public List<MatchHistory> matches { get; set; }
}
Or like this:
public partial class MatchlistDto
{
[JsonProperty("matches")]
public List<MatchHistory> matchhistory { get; set; }
}
2: API returns a MatchlistDto, not a List
Should write this:
MatchlistDto matchHistoryList = JsonConvert.DeserializeObject<MatchlistDto>(PersonalResponse2);

Related

How to get certain properties of the array from Model to ViewModel without Json parseerror (Asp.Net Core MVC)

I'm currently working on the Asp.Net Core MVC project and have the following Message class
public class Message
{
public int Id { get; set; }
public string SenderId { get; set; }
[ForeignKey("SenderId")]
public virtual User Sender { get; set; }
public string RecipientId { get; set; }
[ForeignKey("RecipientId")]
public virtual User Recipient { get; set; }
public string Content { get; set; }
public bool IsRead { get; set; }
public DateTime? DateRead { get; set; }
public DateTime MessageSent { get; set; }
public bool SenderDeleted { get; set; }
public bool RecipientDeleted { get; set; }
}
Using the mapper, I get the below ViewModel for the Message review:
public class MessageReviewViewModel
{
public int Id { get; set; }
public string SenderId { get; set; }
[ForeignKey("SenderId")]
public virtual User Sender { get; set; }
public string RecipientId { get; set; }
[ForeignKey("RecipientId")]
public virtual User Recipient { get; set; }
public string Content { get; set; }
public bool IsRead { get; set; }
public DateTime? DateRead { get; set; }
public DateTime MessageSent { get; set; }
}
Now, I would like to get actually the Recipient and Sender users, however the reason I have such a simple MessageReviewViewModel is because I'm getting the list of this view models and with this users json throws an error & without it I have successfull result.
However, the problem is, that for the proper display in the Inbox view I still need the certain properties of Recipient and Sender user's (their main photo url, username & etc).
My mapper configuration is as below to get the messages from the repository:
public async Task<IEnumerable<MessageReviewViewModel>> GetMessagesForUserByUserId(string userId)
{
var messages = await messageRepository.GetMessagesForUser(userId);
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Message, MessageReviewViewModel>();
cfg.IgnoreUnmapped();
});
IMapper mapper = config.CreateMapper();
var messageList = mapper.Map<IEnumerable<Message>, IEnumerable<MessageReviewViewModel>>(messages);
return messageList;
}
In the react component (I have integrated react.js in the asp.net core mvc) once it did mount I make a get request to get the messages list as below and setState messagesList to the received array.
componentDidMount() {
const xhr = new XMLHttpRequest();
xhr.open('get', "/Messages/GetMessages", true);
xhr.onload = () => {
const data = JSON.parse(xhr.responseText);
this.setState({ messagesList: data });
console.log(this.state.messagesList);
};
xhr.send();
}
And this is the action in the controller, that is being called:
[HttpGet]
public async Task<IActionResult> GetMessages()
{
var userFromRepo = await userManager.FindByNameAsync(User.Identity.Name);
var messages = await messagesService.GetMessagesForUserByUserId(userFromRepo.Id);
var sortedMessageList = messages.OrderByDescending(m => m.MessageSent);
return Json(sortedMessageList);
}
As I mentioned, it all works without any problem unless there are no virtual User Sender and virtual User Recipient in the MessageReviewViewModel. Once I have them in code, this is the error I get:
Probably it is worth to mention, that the User class objects (in my scenario Sender & Recipient for example) also have the virtual properties inside and I thought that it may be problem for Json parse these objects, which have other objects as property.
Could you please advise how I can include these properties in the ViewModel so neither mapper nor JSON throw any error? I'm okay even to get only selected properties of the obje (for example just string username, mainphoto url & etc).
It is also ok, if there is any Json method, that will solve this parseError with virtual users included in the ViewModel
I figured it out after finding that mapper can also be configured to the level that is required by the user
The Message model is as below as previously
public class Message
{
public int Id { get; set; }
public string SenderId { get; set; }
[ForeignKey("SenderId")]
public virtual User Sender { get; set; }
public string RecipientId { get; set; }
[ForeignKey("RecipientId")]
public virtual User Recipient { get; set; }
public string Content { get; set; }
public bool IsRead { get; set; }
public DateTime? DateRead { get; set; }
public DateTime MessageSent { get; set; }
public bool SenderDeleted { get; set; }
public bool RecipientDeleted { get; set; }
}
And the MessageReviewViewModel changed to below:
public class MessageReviewViewModel
{
public int Id { get; set; }
public string SenderId { get; set; }
public string SenderUsername { get; set; }
public string SenderMainPhotoUrl { get; set; }
public string RecipientId { get; set; }
[ForeignKey("RecipientId")]
public string RecipientUsername { get; set; }
public string RecipientMainPhotoUrl { get; set; }
public string Content { get; set; }
public bool IsRead { get; set; }
public DateTime? DateRead { get; set; }
public DateTime MessageSent { get; set; }
}
Only for the mapper the configuration was required as below:
public async Task<IEnumerable<MessageReviewViewModel>> GetMessagesForUserByUserId(string userId)
{
var messages = await messageRepository.GetMessagesForUser(userId);
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Message, MessageReviewViewModel>()
.ForMember(destination=>destination.RecipientUsername,map=>map.MapFrom(
source=>source.Recipient.UserName)) //gets only string for username instead of whole User model
.ForMember(destination=> destination.RecipientMainPhotoUrl,map=>map.MapFrom(
source=>source.Recipient.MainProfilePicture)) //gets only string for profile picture instead of whole User model
.ForMember(destination=>destination.SenderUsername,map=>map.MapFrom(
source=>source.Sender.UserName))
.ForMember(destination=>destination.SenderMainPhotoUrl,map=>map.MapFrom(
source=>source.Sender.MainProfilePicture));
cfg.IgnoreUnmapped();
});
IMapper mapper = config.CreateMapper();
var messageList = mapper.Map<IEnumerable<Message>, IEnumerable<MessageReviewViewModel>>(messages);
return messageList;
}
As all received data now are only strings, Json has no problem parsing it

Can't get API input list and convert it to json and get its contents

I have an API that as an input I have:
myMedicineJsonList=[{"medicineType":"ketamine","medicineDose":"5 drops","medicineDiode":"IV"},{"medicineType":"adrenaline","medicineDose":"5 drops","medicineDiode":"IV"}]
I need to get its contents and save it in a table in a database.
Currently I'm using the following code:
public partial class medicines
{
public int medicine{ get; set; }
public String medicineType { get; set; }
public String medicineDosage { get; set; }
public String medicinePlace { get; set; }
}
public System.Web.Http.Results.JsonResult<String> Insert_call_info( List<String> medicineList)
{
using (EMSMVCEntities entities = new EMSMVCEntities())
{
entities.Configuration.ProxyCreationEnabled = false;
try
{
var myMedicineJson = JsonConvert.SerializeObject(medicineList);
var myMedicineJsonList = JsonConvert.DeserializeObject<medicines>(myMedicineJson);
var medications = myMedicineJsonList.Value<JObject>("Medicine").ToObject<List<medicines>>();
var medicationsdb = entities.Set<Call_info_Medicines>();
...
}
}
}
However in myMedicineJsonList or in medications I can't get the contents of medicineList to store them in a table.
The table I want to store it is the following:
public partial class Call_info_Medicines
{
public int medicine_info_id { get; set; }
public string medicine { get; set; }
public string medicineType { get; set; }
public string medicineDosage { get; set; }
public string medicinePlace { get; set; }
}
I need to store it using the following line is the previous code snipset.
var medicationsdb = entities.Set<Call_info_Medicines>();
I found the following solution:
public class RootObject
{
public List<medicines> Medicine { get; set; }
}
var medResult = JsonConvert.DeserializeObject<RootObject>(medicineList);
var medicineTypeL = medResult.Medicine.Select(p => p.medicineType).ToList();
var medicineDosageL = medResult.Medicine.Select(p => p.medicineDosage).ToList();
var medicinePlaceL = medResult.Medicine.Select(p => p.medicinePlace).ToList();

Implementing deserialization with RestSharp and Newtonsoft.Json

I am rather new to c# but I am building something to help me at work. We have a REST API which I am trying to tap into but I am having issues when it comes to deserializing the response.
My code:
namespace BSRestCleint
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string key = "xxxxxxxx";
string endPoint = "https://api.broadsign.com:10889/rest";
private void bRun_Click(object sender, EventArgs e)
{
var client = new RestClient(endPoint);
var request = new RestRequest("/host/v14/by_id", Method.GET);
request.AddHeader("accept", "application/json");
request.AddHeader("Authorization", "Bearer " + key);
request.AddParameter("domain_id", "103947039");
request.AddParameter("ids", "195392183");
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
request.RequestFormat = DataFormat.Json;
var response = client.Execute<Host>(request);
var host = JsonConvert.DeserializeObject<Host>(response.Content);
oResponse.Text = host.Name;
}
}
}
And this is my class:
namespace BSRestCleint
{
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Runtime.Serialization.Json;
using System.IO;
public partial class Host
{
[JsonProperty("config_profile_bag_id")]
public long ConfigProfileBagId { get; set; }
[JsonProperty("container_id")]
public long ContainerId { get; set; }
[JsonProperty("db_pickup_tm_utc")]
public string DbPickupTmUtc { get; set; }
[JsonProperty("discovery_status")]
public long DiscoveryStatus { get; set; }
[JsonProperty("display_unit_id")]
public long DisplayUnitId { get; set; }
[JsonProperty("domain_id")]
public long DomainId { get; set; }
[JsonProperty("geolocation")]
public string Geolocation { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("nscreens")]
public long Nscreens { get; set; }
[JsonProperty("public_key_fingerprint")]
public string PublicKeyFingerprint { get; set; }
[JsonProperty("remote_clear_db_tm_utc")]
public string RemoteClearDbTmUtc { get; set; }
[JsonProperty("remote_reboot_tm_utc")]
public string RemoteRebootTmUtc { get; set; }
[JsonProperty("volume")]
public long Volume { get; set; }
}
}
Finally the returning json:
{
"not_modified_since":"2018-06-05T22:22:18Z",
"host":[
{
"active":true,
"config_profile_bag_id":0,
"container_id":0,
"db_pickup_tm_utc":"2018-01-11T10:12:55",
"discovery_status":0,
"display_unit_id":0,
"domain_id":103947039,
"geolocation":"(0,0)",
"id":195392183,
"license_end_date":null,
"licensed":true,
"name":"Broadsign Services - Mathias - 16x64",
"nscreens":0,
"primary_mac_address":"00:0c:29:e0:e6:22",
"public_key_fingerprint":"REDACTED",
"remote_clear_db_tm_utc":"1970-01-01T00:00:00",
"remote_reboot_tm_utc":"2017-12-12T10:17:23",
"secondary_mac_address":"",
"volume":-1
}
]
}
I know that if I only process this part my code works:
{
"active":true,
"config_profile_bag_id":0,
"container_id":0,
"db_pickup_tm_utc":"2018-01-11T10:12:55",
"discovery_status":0,
"display_unit_id":0,
"domain_id":103947039,
"geolocation":"(0,0)",
"id":195392183,
"license_end_date":null,
"licensed":true,
"name":"Broadsign Services - Mathias - 16x64",
"nscreens":0,
"primary_mac_address":"00:0c:29:e0:e6:22",
"public_key_fingerprint":"REDACTED",
"remote_clear_db_tm_utc":"1970-01-01T00:00:00",
"remote_reboot_tm_utc":"2017-12-12T10:17:23",
"secondary_mac_address":"",
"volume":-1
}
I'd like to know how I could make my code work to handle the whole json so that I don't need to regex the returning value. Some of the responses would return multiple instances unlike there where there's only 1. It's probably a very simple solution but my grasp of the language is rather minute as I am new to it.
Any help would be appreciated.
Since, you are getting the host as array inside the another root object so you can define a new class as which is wrapping Host (array)
public class RootObject
{
public DateTime not_modified_since { get; set; }
public List<Host> Host { get; set; }
}
deserialization code need to be updated as
var root = JsonConvert.DeserializeObject<RootObject>(response.Content);
If you see, here deserializtion will happen for RootObject instead of Host.
Now, to get all hosts, use the below code:
var hosts = root.Host;
Or the first host from received hosts
var firstHost = root.Host.First();
You can extract it like this, without introducing new class:
var js = JObject.Parse(response.Content);
var hosts = JArray.Parse(obj["host"].ToString());
foreach (JObject host in hosts)
{
var h = JsonConvert.DeserializeObject<Host>(host)
//do what you need to do with host
}
You mentioned that there can be multiple hosts, so, you have to convert it to JArray, and loop through the array.
use this as your Host class instead (renamed to RootObject)
public partial class RootObject
{
[JsonProperty("not_modified_since")]
public DateTimeOffset NotModifiedSince { get; set; }
[JsonProperty("host")]
public List<Host> Host { get; set; }
}
public partial class Host
{
[JsonProperty("active")]
public bool Active { get; set; }
[JsonProperty("config_profile_bag_id")]
public long ConfigProfileBagId { get; set; }
[JsonProperty("container_id")]
public long ContainerId { get; set; }
[JsonProperty("db_pickup_tm_utc")]
public DateTimeOffset DbPickupTmUtc { get; set; }
[JsonProperty("discovery_status")]
public long DiscoveryStatus { get; set; }
[JsonProperty("display_unit_id")]
public long DisplayUnitId { get; set; }
[JsonProperty("domain_id")]
public long DomainId { get; set; }
[JsonProperty("geolocation")]
public string Geolocation { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("license_end_date")]
public object LicenseEndDate { get; set; }
[JsonProperty("licensed")]
public bool Licensed { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("nscreens")]
public long Nscreens { get; set; }
[JsonProperty("primary_mac_address")]
public string PrimaryMacAddress { get; set; }
[JsonProperty("public_key_fingerprint")]
public string PublicKeyFingerprint { get; set; }
[JsonProperty("remote_clear_db_tm_utc")]
public DateTimeOffset RemoteClearDbTmUtc { get; set; }
[JsonProperty("remote_reboot_tm_utc")]
public DateTimeOffset RemoteRebootTmUtc { get; set; }
[JsonProperty("secondary_mac_address")]
public string SecondaryMacAddress { get; set; }
[JsonProperty("volume")]
public long Volume { get; set; }
}
}
then deserialize
var rootObject = JsonConvert.DeserializeObject<RootObject>(response.Content);
var hosts = rootObject .Host;

RestSharp JSON List Deseralization

I launched this code:
var responseSection = client.Execute<List<SectionResponse>>(requestSection);
The response I should get:
[
{"SectionId":644852,"Name":"GDTC-MOBL-01-15W","Description":{"Text":"","Html":""},"Enrollments":[]},
{"SectionId":644853,"Name":"GDTC-MOBL-02-15W","Description":{"Text":"","Html":""},"Enrollments":[]}
]
The groups of my data classes:
public class SectionResponse
{
public List<SectionList> sectionList { get; set; }
}
public class SectionList
{
public int SectionId { get; set; }
public string Name { get; set; }
public Description_t Description { get; set; }
public List<Enrollments_t> Enrollments { get; set; }
}
public class Description_t
{
public string Text { get; set; }
public string Html { get; set; }
}
public class Enrollments_t
{
}
The problem is it attempts twice (two lists) but each request returns null data.
What should I do to get data?
Thanks in advance,
Phillip
You're saying you want a list of SectionResponses, which itself contains a list, so basically you're saying you want a list of lists, which doesn't match the response.
Try either this:
var responseSection = client.Execute<SectionResponse>(requestSection);
or this:
var responseSection = client.Execute<List<SectionList>>(requestSection);

Attempt to access the method failed: System.Collections.Generic.List`1..ctor()

I've this code through which I am retrieveing json data from my Localhost.But it is giving the error mentioned in my title.When I hover over the response while debugging.It shows me the correct response.I am using JSON.NET to parse json response.
var response = reader.ReadToEnd();
List<Company> cLst = JsonConvert.DeserializeObject<List<Company>>(response); //Error
this.Dispatcher.BeginInvoke(() =>
{
foreach (Company c in cLst)
{
ListBoxItemControl Li = new ListBoxItemControl();
Li.CompanyNameTextBlock.Text = c.CompanyName;
Li.PromotionTextBlock.Text = c.PromotionText;
listBox1.Items.Add(Li);
}
});
Here is the Company Class.
class Company
{
public string CompanyName {get; set;}
public string CompanySlogan { get; set; }
public string CompanyDescription { get; set; }
public string CompanyRating { get; set; }
public string CompanyDpPath { get; set; }
public string CompanyOtherInfo { get; set; }
public string CompanyFollowers { get; set; }
public int CompanyID { get; set; }
public int PromotionID { get; set; }
public string PromotionText { get; set; }
public string PromotionRating { get; set; }
public string PromotionPicPath { get; set; }
public string PromotionTitle { get; set; }
public int PromotionLikes { get; set; }
public int PromotionComments { get; set; }
}
Try making the Company class public
Take another class like,
public class RootObject
{
public List<Company> companies;
}
And then modify your code like this,
var jsonData = JsonConvert.DeserializeObject<RootObject>(response);
List<Company> cLst = jsonData.companies;
Try this and let me know.