RestSharp JSON List Deseralization - json

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);

Related

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

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);

Deserializing JSON from URL - how do I add it to multiple objects

So basically I ran the JSON through jsonUtils which created an object, which turned out to be several objects.
So 2 questions please:
How to best populate objects from URL?
Can I select which objects to populate, i.e. I don't want to do all 20 objects?
In advance, thank you!!
WebClient client = new WebClient();
string myJSON = client.DownloadString("https://someURL.geojson");
var myClass = Newtonsoft.Json.JsonConvert.DeserializeObject(myJSON);
Console.Write(myClass.ToString());
public class PrecipType
{
public string units { get; set; }
public string value { get; set; }
}
public class Press
{
public string units { get; set; }
public string value { get; set; }
}
public class Atmo
{
public AirTemperature air_temp{ get; set; }
public Dewpoint dew_point{ get; set; }
public Wind { get; set; }
public Pressure pressure { get; set; }
}
public class ObsTime
{
public string units { get; set; }
public string value { get; set; }
}

Extracting JSON data using Newtonsoft in xamarin.android

Hello I am getting JSON data from server and i want to extract that JSON in Xamarin. How can i parse that JSON using NewTonSoft
below is the JSON responce i receive
[
{
"Id": 5,
"AlbumKey": "2REC2ZDSFK",
"ZipFillPath": "aaaa#gmail.com\\2REC2ZDSFK",
"NoOfPages": 3,
"EmailID": "aaaa#gmail.com"
}
]
This should be your Model
public class RootObject
{
public int Id { get; set; }
public string AlbumKey { get; set; }
public string ZipFillPath { get; set; }
public int NoOfPages { get; set; }
public string EmailID { get; set; }
}
Then
RootObject myObj = JsonConvert.DeserializeObject<RootObject>(json);
If your json is a List of objects, something like
List<RootObject> myListObj = JsonConvert.DeserializeObject<List<RootObject>>(json);
public class yourClass
{
public int Id { get; set; }
public string AlbumKey { get; set; }
public string ZipFillPath { get; set; }
public int NoOfPages { get; set; }
public string EmailID { get; set; }
}
Considering this as your model class you can
var responseText= JsonConvert.DeserializeObject<yourClass>(jsonResponse);
Then depending on if its a list or a not you can get the data from it
In case you are unable to find the class what you can do is check if the namespace of your current class and that class is the same.

JSON.NET Error reading string. Unexpected token: StartObject. Path 'responseData',

I am trying to deserialize this link , but I keep getting this error.
Error reading string. Unexpected token: StartObject. Path 'responseData'.
From what i have googled, the problem seems to be the setup of my object I'm trying to deserialize into. Below is my class:
public class FeedSearchResult
{
[JsonProperty("responseData")]
public String ResponseData { get; set; }
[JsonProperty("query")]
public String Query { get; set; }
[JsonProperty("entries")]
public string[] Entries { get; set; }
[JsonProperty("responseDetails")]
public object ResponseDetails { get; set; }
[JsonProperty("responseStatus")]
public String ResponseStatsu { get; set; }
}
public class ResultItem
{
[JsonProperty("title")]
public String Title { get; set; }
[JsonProperty("url")]
public String Url { get; set; }
[JsonProperty("link")]
public String Link { get; set; }
}
What am I doing wrong in my class? Any help would be greatly appreciated.
Your data model only has two levels of nesting, but the JSON returned has three. If you look at the formatted JSON using https://jsonformatter.curiousconcept.com/ you will see:
{
"responseData":{
"query":"Official Google Blogs",
"entries":[
{
"url":"https://googleblog.blogspot.com/feeds/posts/default",
"title":"\u003cb\u003eOfficial Google Blog\u003c/b\u003e",
"contentSnippet":"\u003cb\u003eOfficial\u003c/b\u003e weblog, with news of new products, events and glimpses of life inside \u003cbr\u003e\n\u003cb\u003eGoogle\u003c/b\u003e.",
"link":"https://googleblog.blogspot.com/"
},
In particular your data model has responseData as a String when it needs to be a contained object. This is the specific cause of the exception.
If you upload the JSON to http://json2csharp.com/ you will get the following data model, which can be used to deserialize this JSON:
public class ResultItem
{
public string url { get; set; }
public string title { get; set; }
public string contentSnippet { get; set; }
public string link { get; set; }
}
public class ResponseData
{
public string query { get; set; }
public List<ResultItem> entries { get; set; }
}
public class RootObject
{
public ResponseData responseData { get; set; }
//Omitted since type is unclear.
//public object responseDetails { get; set; }
public int responseStatus { get; set; }
}

How can I deserialization JSON in Windows Phone?

The first JSON is look like this
The second JSON is look like this
How can I deserialize them? I have been follow this example but it's not working.
Here's my code.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
var w = new WebClient();
Observable
.FromEvent<DownloadStringCompletedEventArgs>(w, "DownloadStringCompleted")
.Subscribe(r =>
{
var deserialized =
JsonConvert.DeserializeObject<List<Place>>(r.EventArgs.Result);
PlaceList.ItemsSource = deserialized;
});
w.DownloadStringAsync(
new Uri("http://mobiilivantaa.lightscreenmedia.com/api/place"));
//For 2nd JSON
//w.DownloadStringAsync(
//new Uri("http://mobiilivantaa.lightscreenmedia.com/api/place/243"));
}
These are classes for 1st JSON.
public class Place
{
public string id { get; set; }
public string title { get; set; }
public string latitude { get; set; }
public string longitude { get; set; }
public string www { get; set; }
}
public class RootObjectJSON1
{
public List<Place> Places { get; set; }
}
These are classes for JSON2
public class Address
{
public string street { get; set; }
public string postal_code { get; set; }
public string post_office { get; set; }
}
public class Image
{
public string id { get; set; }
public string filename { get; set; }
public string path { get; set; }
}
public class RootObjectJSON2
{
public string id { get; set; }
public string title { get; set; }
public string description { get; set; }
public string latitude { get; set; }
public string longitude { get; set; }
public string www { get; set; }
public string phone { get; set; }
public string email { get; set; }
public string contact_person { get; set; }
public Address address { get; set; }
public List<Image> images { get; set; }
}
it looks that you should be deserializing object RootObjectJSON1 or RootObjectJSON2, e.g.:
var deserialized = JsonConvert.DeserializeObject<RootObjectJSON1>(r.EventArgs.Result);
Also it seems that collection Places should be with lowercase p at beginning or you need to tell Json.NET that this property should be deserialized with different name, e.g.:
[JsonProperty(PropertyName="places")]
public List<Place> Places { get; set; }
Generally I tend to use arrays for deserialization (from my experience works better) so I'll suggest to rewrite it to this:
public class RootObjectJSON1
{
public Place[] places { get; set; }
}
There is very good tool named json2csharp available at http://json2csharp.com/ - just put sample of JSON there and it will spit out classes in C# (doesn't detect DateTime so you might need to change that).