Deserialize OneNote Notebooks API Response - json

I'm getting an empty object when I try to Deserialize a OneNote GetAllNotebooks query.
string[] tempCapture = null;
var url = new Uri("https://graph.microsoft.com/v1.0/me/onenote/notebooks");
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
if (IsAuthenticated)
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
}
var response = await client.GetAsync(url);
var result = await response.Content.ReadAsStringAsync();
tbResponse.Text = result.ToString();
DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(List<Value>));
MemoryStream stream1 = new MemoryStream(Encoding.UTF8.GetBytes(tbResponse.Text.ToString()));
var obj1 = (List<Value>)ser1.ReadObject(stream1);
I'm trying to get a list of notebooks, names, links to add to a database. And my table structure matches the class below.
Here is my OneNote API class
public class Value
{
public bool isDefault { get; set; }
public string userRole { get; set; }
public bool isShared { get; set; }
public string sectionsUrl { get; set; }
public string sectionGroupsUrl { get; set; }
public Links links { get; set; }
public string name { get; set; }
public string self { get; set; }
public string createdBy { get; set; }
public string lastModifiedBy { get; set; }
public string lastModifiedTime { get; set; }
public string id { get; set; }
public string createdTime { get; set; }
}
Here is my new code with the RootObject. I'm still getting an error. It is in the catch exception.
var test = await client.GetAsync(url);
string testStr = await test.Content.ReadAsStringAsync();
DataContractJsonSerializer serial = new DataContractJsonSerializer(typeof(RootObject));
MemoryStream testStream = new MemoryStream(Encoding.UTF8.GetBytes(testStr));
try
{
var objx = (List<RootObject>)serial.ReadObject(testStream);
}
catch(Exception ex)
{
ex.ToString();
//"There was an error deserializing the object of type OneNoteSOAP2.RootObject. End element 'createdBy' from namespace '' expected. Found element 'user' from namespace ''."
}

You can use http://json2csharp.com/. Basically, just copy the value of our JSON being returned, and use the classes generated by this website. Use RootObject to deserialize.
I ran this for you and obtained these classes:
public class OneNoteClientUrl
{
public string href { get; set; }
}
public class OneNoteWebUrl
{
public string href { get; set; }
}
public class Links
{
public OneNoteClientUrl oneNoteClientUrl { get; set; }
public OneNoteWebUrl oneNoteWebUrl { get; set; }
}
public class Value
{
public string id { get; set; }
public string self { get; set; }
public string createdTime { get; set; }
public string name { get; set; }
public string createdBy { get; set; }
public string lastModifiedBy { get; set; }
public string lastModifiedTime { get; set; }
public bool isDefault { get; set; }
public string userRole { get; set; }
public bool isShared { get; set; }
public string sectionsUrl { get; set; }
public string sectionGroupsUrl { get; set; }
public Links links { get; set; }
}
public class RootObject
{
public List<Value> value { get; set; }
}

Related

Object is always empty when deserialize on xamarin service

Have this service built on a xamarin app:
public class OpenWeatherMap<T>
{
private const string OpenWeatherApi = "http://api.openweathermap.org/data/2.5/weather?q=";
private const string Key = "653b1f0bf8a08686ac505ef6f05b94c2";
HttpClient _httpClient = new HttpClient();
// aqui podemos enviar directo a una ciudad hardcoded
public async Task<T> GetAllWeathers(string city)
{
var json = await _httpClient.GetStringAsync(OpenWeatherApi + city + "&APPID=" + Key);
var getWeatherModels = JsonConvert.DeserializeObject<T>(json);
return getWeatherModels;
}
}
When i check the model object is always empty. JSON is fine and my class matches perfectly my JSON model. I'm using Newtonsoft.Json.
This is my model:
public class WeatherMainModel
{
[JsonProperty("coord")]
public Coord Coord { get; set; }
[JsonProperty("weather")]
public WeatherSubDetails[] Weather { get; set; }
[JsonProperty("base")]
public string Base { get; set; }
[JsonProperty("main")]
public Main Main { get; set; }
[JsonProperty("visibility")]
public string Visibility { get; set; }
[JsonProperty("wind")]
public WeatherWindDetails Wind { get; set; }
[JsonProperty("clouds")]
public Clouds Clouds { get; set; }
[JsonProperty("dt")]
public string Dt { get; set; }
[JsonProperty("sys")]
public WeatherSysDetails Sys { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("cod")]
public string Cod { get; set; }
}
public partial class Clouds // new
{
[JsonProperty("all")]
public string All { get; set; }
}
public partial class Coord // new
{
[JsonProperty("lon")]
public string Lon { get; set; }
[JsonProperty("lat")]
public string Lat { get; set; }
}
public partial class Main
{
[JsonProperty("temp")]
public string Temp { get; set; }
[JsonProperty("pressure")]
public string Pressure { get; set; }
[JsonProperty("humidity")]
public string Humidity { get; set; }
[JsonProperty("temp_min")]
public string TempMin { get; set; }
[JsonProperty("temp_max")]
public string TempMax { get; set; }
}
public partial class WeatherSysDetails
{
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("message")]
public string Message { get; set; }
[JsonProperty("country")]
public string Country { get; set; }
[JsonProperty("sunrise")]
public string Sunrise { get; set; }
[JsonProperty("sunset")]
public string Sunset { get; set; }
}
public partial class WeatherSubDetails
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("main")]
public string Main { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("icon")]
public string Icon { get; set; }
}
public partial class WeatherWindDetails
{
[JsonProperty("speed")]
public string Speed { get; set; }
[JsonProperty("deg")]
public string Deg { get; set; }
}
I'm using visual studio community set for Latin America (Chile), so i tried changing every decimal field on the JSON to string on the model to avoid comma separation problems, but still, my object is coming empty no matter the JSON i inject to the deserializer.
Thanks in advance.

Deserialize multi-part JSON with DataContractJsonSerializer

I'm fairly new to the awesomeness that is JSON - I'm using the DataContractJsonSerializer. I cannot get the multiple instances of the Customer objects into the list.
The Attributes work as expected but there are no Customer objects in my List..??
{
"#attributes":
{"count":"2",
"offset":"0",
"limit":"100"
},
"Customer":
{
"firstName":"cust ",
"lastName":"one",
"title":"Owner",
"company":"CustOne Plants",
"companyRegistrationNumber":"",
"vatNumber":"",
"creditAccountID":"1",
"customerTypeID":"4",
"discountID":"0",
"taxCategoryID":"0",
"customerID":"1",
"createTime":"2017-06-19T23:36:11+00:00",
"timeStamp":"2017-06-20T18:55:11+00:00",
"archived":"false"
}
"Customer":
{
"firstName":"cust ",
"lastName":"two",
"title":"Owner",
"company":"CustTwo House of Games",
"companyRegistrationNumber":"",
"vatNumber":"",
"creditAccountID":"1",
"customerTypeID":"4",
"discountID":"0",
"taxCategoryID":"0",
"customerID":"1",
"createTime":"2017-06-19T23:36:11+00:00",
"timeStamp":"2017-06-20T18:55:11+00:00",
"archived":"false"
}
}
.NET code:
StreamReader stream = new StreamReader(#"C:\TMC Projects\PotteryManufacturing\CustomerJSON.txt");
string text = stream.ReadToEnd();
stream.Close();
byte[] byteArray = Encoding.UTF8.GetBytes(text);
MemoryStream stream1 = new MemoryStream(byteArray);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(CustomersRoot));
var varInfo = serializer.ReadObject(stream1) as CustomersRoot;
stream1.Close();
and finally my classes/data contracts/data members:
[DataContract]
public class CustomersRoot
{
private List<Customer> m_Customers;
public CustomersRoot() { this.Customer = new List<Customer>(); }
[DataMember(Name ="#attributes")]
public Attributes attrs { get; set; }
[DataMember(Name = "Customer")]
public List<Customer> Customer
{
get { return m_Customers; }
set { m_Customers = value; }
}
}
[DataContract]
public class Customer
{
[DataMember(Name ="firstName")]
public string firstName { get; set; }
[DataMember(Name = "lastName")]
public string lastName { get; set; }
[DataMember(Name = "title")]
public string title { get; set; }
[DataMember(Name = "company")]
public string company { get; set; }
[DataMember(Name = "companyRegistrationNumber")]
public string companyRegistrationNumber { get; set; }
[DataMember(Name = "vatNumber")]
public string vatNumber { get; set; }
[DataMember(Name = "creditAccountID")]
public int creditAccountID { get; set; }
[DataMember(Name = "customerTypeID")]
public int customerTypeID { get; set; }
[DataMember(Name = "discountID")]
public int discountID { get; set; }
[DataMember(Name = "taxCategoryID")]
public int taxCategoryID { get; set; }
[DataMember(Name = "customerID")]
public int customerID { get; set; }
[DataMember(Name = "createTime")]
public string createTime { get; set; }
[DataMember(Name = "timeStamp")]
public string timeStamp { get; set; }
[DataMember(Name = "archived")]
public bool archived { get; set; }
}
[DataContract]
public class Attributes
{
[DataMember(Name = "count")]
public int count { get; set; }
[DataMember(Name = "offset")]
public int offset { get; set; }
[DataMember(Name = "limit")]
public int limit { get; set; }
}
I figured out what's going on here - the call can sometimes return an array of Customer objects (not formatted correctly above) OR a single instance of the object. When the web service returns a single Customer instance, the List code does not work. I will have to check on how to deal w/ this issue.

{"No parameterless constructor defined for type of 'System.String[]'."} while deserailsing json data

This is my controller
[NoCache]
public ActionResult SaveAssociate(string data)
{
JavaScriptSerializer json = new JavaScriptSerializer();
List<string> mystring = json.Deserialize<List<string>>(data);
return Content("Hai");
}
Expression data
value :
[{"AssetName":"8888","AssetNumber":"8888","Classification":null,"ParentAsset":null,"SerialNumber":"8888","ParentCompany":"JPL Holdings","Barcode":null,"RFIDTags":null,"AssetId":"dfe2ae51-f153-4a67-bd3b-0114d8a40751","Notes":null,"Manufacturer":null,"DepartmentId":null,"Department":null,"SupplierId":null,"Supplier":null},{"AssetName":"552014","AssetNumber":"552014","Classification":null,"ParentAsset":"8888","SerialNumber":"552014","ParentCompany":"JPL Holdings","Barcode":null,"RFIDTags":null,"AssetId":"4109ba40-af78-486a-a40e-1d14a2d7b42f","Notes":null,"Manufacturer":null,"DepartmentId":null,"Department":null,"SupplierId":null,"Supplier":null},{"AssetName":"201","AssetNumber":"201","Classification":null,"ParentAsset":null,"SerialNumber":"2011","ParentCompany":"JPL Holdings","Barcode":null,"RFIDTags":null,"AssetId":"3e552280-16df-4c17-a4a5-1f61c4c96835","Notes":null,"Manufacturer":null,"DepartmentId":null,"Department":null,"SupplierId":null,"Supplier":null}]
At this line List<string> mystring = json.Deserialize<List<string>>(data);
am getting
{"No parameterless constructor defined for type of 'System.String[]'."}
even i tried like this
[Serializable]
public class GetUser
{
public GetUserdata[] Data { get; set; }
}
[Serializable]
public class GetUserdata
{
public string AssetName { get; set; }
public string AssetNumber { get; set; }
public string Classification { get; set; }
public string ParentAsset { get; set; }
public string SerialNumber { get; set; }
public string ParentCompany { get; set; }
public string Barcode { get; set; }
public string RFIDTags { get; set; }
public string AssetId { get; set; }
public string Notes { get; set; }
public string Manufacturer { get; set; }
public string DepartmentId { get; set; }
public string Department { get; set; }
public string SupplierId { get; set; }
public string Supplier { get; set; }
}
controller
public ActionResult SaveAssociate(string data)
{
JavaScriptSerializer json = new JavaScriptSerializer();
GetUser mystring = json.Deserialize<GetUser>(data);
return Content("Hai");
}
Am getting error
Type 'AssetTrackingSystem.Model.GetUser' is not supported for deserialization of an array.
Help me
Instead of the above code, could you try:
public ActionResult SaveAssociate(string data)
{
JavaScriptSerializer json = new JavaScriptSerializer();
GetUserdata[] myUsers = json.Deserialize<GetUserdata[]>(data);
return Content("Hai");
}
Because your Json is sent as an array of object not an object of array.
I hope it will help you.

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.

How can I parse the following JSON for WP7 and bind to a listbox?

I'm having some trouble binding this json to a ListBox...The problem seems to happen in the ActivityTrack class/object of the JSON...i'm not sure what is not meshing...
{"collection":[{"type":"track","created_at":"2011/09/18 14:04:00 +0000","origin":{"id":23606164,"created_at":"2011/09/18 14:03:59 +0000","user_id":222927,"duration":342465,"commentable":true,"state":"finished","sharing":"public","tag_list":"garage usgarage soulfulhouse house deephouse deep","permalink":"pablo-cortez-when-i-need-u","description":"","streamable":true,"downloadable":false,"genre":"UK Garage","release":"","purchase_url":null,"label_id":null,"label_name":"","isrc":"","video_url":null,"track_type":"demo","key_signature":"","bpm":null,"title":"Pablo Cortez - When I Need U (Back To 90s Mix)","release_year":null,"release_month":null,"release_day":null,"original_format":"mp3","license":"all-rights-reserved","uri":"https://api.soundcloud.com/tracks/23606164","permalink_url":"http://soundcloud.com/pablocortez/pablo-cortez-when-i-need-u","artwork_url":null,"waveform_url":"http://w1.sndcdn.com/wuiZilHRZhl6_m.png","user":{"id":222927,"permalink":"pablocortez","username":"Pablo Cortez","uri":"https://api.soundcloud.com/users/222927","permalink_url":"http://soundcloud.com/pablocortez","avatar_url":"http://i1.sndcdn.com/avatars-000000771958-y059w8-large.jpg?ca13f03"},"stream_url":"https://api.soundcloud.com/tracks/23606164/stream","user_playback_count":1,"user_favorite":false,"playback_count":28,"download_count":0,"favoritings_count":0,"comment_count":2,"attachments_uri":"https://api.soundcloud.com/tracks/23606164/attachments","sharing_note":{"text":"My new sounds","created_at":"2011/09/18 14:03:59 +0000"}},"tags":"affiliated"}],"next_href":"https://api.soundcloud.com/me/activities/track.json?cursor=86db5e5e-e1fe-11e0-9c69-0f0dad493cfc\\u0026limit=1","future_href":"https://api.soundcloud.com/me/activities/track?uuid%5Bto%5D=2d9c67ee-e22f-11e0-94fa-45aa16adeba3"}
Here is the class structure which i am trying to bind the JSON too
public class Activities
{
public ActivityTrack [] activities { get; set; }
public string next_href { get; set; }
public string future_href { get; set; }
}
public class ActivityTrack
{
public string type { get; set; }
public string created_at { get; set; }
public OriginActivityTrack origin { get; set; }
public string tags { get; set; }
}
public class OriginActivityTrack
{
public string id { get; set; }
public string created_at { get; set; }
public string user_id { get; set; }
public string duration { get; set; }
public string commentable { get; set; }
public string state { get; set; }
public string sharing { get; set; }
public string tag_list { get; set; }
public string permalink { get; set; }
public string description { get; set; }
public string streamable { get; set; }
public string downloadable { get; set; }
public string genre { get; set; }
public string release { get; set; }
public string purchase_url { get; set; }
public string label_id { get; set; }
public string label_name { get; set; }
public string isrc { get; set; }
public string video_url { get; set; }
public string track_type { get; set; }
public string key_signature { get; set; }
public string bpm { get; set; }
public string title { get; set; }
public string release_year { get; set; }
public string release_month { get; set; }
public string release_day { get; set; }
public string original_format { get; set; }
public string license { get; set; }
public string uri { get; set; }
public string permalink_url { get; set; }
public string artwork_url { get; set; }
public string waveform_url { get; set; }
public SmallUser user { get; set; }
public string stream_url { get; set; }
public string user_playback_count { get; set; }
public string user_favorite { get; set; }
public string playback_count { get; set; }
public string download_count { get; set; }
public string favoritings_count { get; set; }
public string comment_count { get; set; }
public string attachments_uri { get; set; }
public SharingNote sharing_note;
}
public class SharingNote
{
public string text { get; set; }
public string created_at { get; set; }
}
public class SmallUser
{
public string id { get; set; }
public string permalink { get; set; }
public string username { get; set; }
public string uri { get; set; }
public string permalink_url { get; set; }
public string avatar_url { get; set; }
}
This is the current code for binding to listbox:
private void ReadCallbackDashboard(IAsyncResult asynchronousResult)
{
lock (locker)
{
try
{
HttpWebRequest request =
(HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response =
(HttpWebResponse)request.EndGetResponse(asynchronousResult);
using (StreamReader streamReader1 =
new StreamReader(response.GetResponseStream()))
{
string resultString = streamReader1.ReadToEnd();
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(resultString)))
{
if (ms != null)
{
var ser = new DataContractJsonSerializer(typeof(Activities));
Activities obj = (Activities)ser.ReadObject(ms);
userDashboardActivities = null;
userDashboardActivities = new ObservableCollection<ActivityTrack>();
for (int i = 0; i < obj.activities.Length; ++i)
{
userDashboardActivities.Add(obj.activities[i]);
}
if (userDashboardActivities.Count() == 0)
{
messageDashboard = "No Tracks Found";
UIThread.Invoke(() => mainMessage.Text = messageDashboard);
}
else
{
messageDashboard = "";
UIThread.Invoke(() => mainMessage.Text = messageDashboard);
UIThread.Invoke(() => dashboardBox.ItemsSource = userDashboardActivities);
}
}
}
}
}
catch (WebException we)
{
UIThread.Invoke(() => MessageBox.Show("Could not retrieve the latest. Internet down? Try a refresh."));
}
}
}
please check it out! Thanks in advance!
Answer as discovered in the comments.
You have called your property activities but the json calls it collection.