JsonConvert.DeserializeObject returns nulls - c#

I have the following code which I am using in an ASP.NET MVC c# application
HttpClient client = new HttpClient();
try
{
var result = client.GetStringAsync(url).Result;
APIReturn = JsonConvert.DeserializeObject<APIReturn>(result);
}
catch
{
}
When I place my breakpoint on the APIReturn = .... line, and I view the contents of result, I see what looks like a valid return from the API call. I even copied the contents of the variable result and applied it to an online json tool. This is what the tool shows:
This is the definition of the APIReturn class:
public class APIReturn
{
public string return_response { get; set; }
public string return_code { get; set; }
public string return_plan_name { get; set; }
public string return_menu_string { get; set; }
public string return_peo_ind { get; set; }
}
At the end of the execution of the code, I look at the values of APIReturn and each field is null.
Any ideas why Json is not parsing the string?
Thank you.

Your json is an array of objects... but you are deserializing it to an object. Change the deserialization to List and should work
var list = JsonConvert.DeserializeObject<List<APIReturn>>(result);

Related

How can parse dynamic json in c#?

Have some json and parse that whit this code:
dynamic json = JsonConvert.DeserializeObject(response.Content);
dynamic result =json.result;
after this line:
dynamic result =json.result;
have this output:
{
{
"321":{
"online_status":true,
"basic_info":{
"status":"Recharged",
"group_name":"IRN-UV002-M01",
"isp_name":"Main",
"creation_date":"2017-09-05 08:19:32",
"recharge_deposit":0.0,
"user_id":321,
"nearest_exp_date":"2018-02-22 10:21:00",
"credit":20387.775145462037,
"deposit":0.0,
"isp_id":0,
"group_id":72
},
"user_repr":"10001168-2100104f4Y8-FTTH",
}
}
}
and now want to get user_id from that json,how can i write code for that purpose?thanks.
The better way would be to deseralize this into a strongly typed object.
But for you you can use the JObject class to do something like the following (note not tested, but you should understand the concept):
dynamic result = JObject.Parse(source);
int id = result.321.basic_info.user_id;
You probably want to do something like this:
var yourInstance = JsonConvert.DeserializeObject<YourClass>(responseJson);
For that, you need to define a class YourClass and related sub-classes which have properties matching the values returned in the JSON data, i.e. something like:
public class YourClass {
public bool online_status { get; set; }
public BasicInfo basic_info { get; set; }
public string user_repr { get; set; }
}
public class BasicInfo {
public string status { get; set; }
public string group_name{ get; set; }
public string isp_name{ get; set; }
public DateTime creation_date{ get; set; }
public string group_name{ get; set; }
// ...etc.
}
With this in place, JsonConvert should be able to understand and parse your data to the correct object.
This is just a rough example, but it should get you on your way.
Another way is to use JObject to hold the string.
var str = "{\"321\":{\"online_status\":true,\"basic_info\":{\"status\":\"Recharged\",\"group_name\":\"IRN-UV002-M01\",\"isp_name\":\"Main\",\"creation_date\":\"2017-09-05 08:19:32\",\"recharge_deposit\":0.0,\"user_id\":321,\"nearest_exp_date\":\"2018-02-22 10:21:00\",\"credit\":20387.775145462037,\"deposit\":0.0,\"isp_id\":0,\"group_id\":72},\"user_repr\":\"10001168-2100104f4Y8-FTTH\"}}";
var obj = JObject.Parse(str);
var userId = obj["321"]["basic_info"]["user_id"].ToString();

Unable to use JSON data with Newtonsoft.Json in WPF

I am retrieving data from office365 api. The response is in JSON format. I want to get data like Id, DisplayName etc. into variables but not getting the right way to do it. Following this link. I'm new to API and JSON. Will Appreciate pointers as well towards best learning links.Sample JSON below for listing sub folders of Inbox folder.
Response JSON data.
{"#odata.context":"https://outlook.office365.com/api/v1.0/$metadata#Me/Folders('Inbox')/ChildFolders","value":
[
{"#odata.id":"https://outlook.office365.com/api/v1.0/Users('sample.user#demosite.com')/Folders('AAMkADBjMGZiZGFlLTE4ZmEtNGRlOS1iMjllLTJmsdfsdfdDSFSDFDFDF=')",
"Id":"AAMkADBjMdfgdfgDFGDFGDFGdfGDFGDFGDFGGDzrACAAB4xqMmAAA=",
"DisplayName":"SampleFolder","ParentFolderId":"AAMkADBjMGZiZGFlLTE4ZmEtNGRlOS1sdsDFSDFSDFSDFSDFSDFDFDFrACAAAAAAEMAAA=","ChildFolderCount":0,"UnreadItemCount":8,"TotalItemCount":94},
{"#odata.id":"https://outlook.office365.com/api/v1.0/Users('sample.user#demosite.com')/Folders('AAMkADBjMGZiZGFlLTE4ZmEasdasdasdASDASDASDASDSADDASDASDAB4xqMnAAA=')",
"Id":"AAMkADBjMGZiZGFlLTE4ZmEtNGRlOS1iMjllLTJmOGZkNGRhZmIzNQAuAasdASDASDASDASEDASDASDxSEHjzrACAAB4xqMnAAA=",
"DisplayName":"AnotherSampleFolder","ParentFolderId":"AAMkADBjMGZiZGFlLTE4ZmEtNGRlOS1sdsDFSDFSDFSDFSDFSDFDFDFrACAAAAAAEMAAA=","ChildFolderCount":0,"UnreadItemCount":21,"TotalItemCount":75}
]
}
The C# code using to parse JSON and find the required data.
HttpResponseMessage response = httpClient.SendAsync(request).Result;
if (!response.IsSuccessStatusCode)
throw new WebException(response.StatusCode.ToString() + ": " + response.ReasonPhrase);
string content = response.Content.ReadAsStringAsync().Result;
JObject jResult = JObject.Parse(content);
if (jResult["odata.error"] != null)
throw new Exception((string)jResult["odata.error"]["message"]["value"]);
//Attempt one - using dynamic [NOT WORKING - getting NULL values in the variables]
dynamic results = JsonConvert.DeserializeObject<dynamic>(content);
var folderName = results.Id;
var folderId = results.Name;
//Attempt two - [Not working - Throwing exception -
//Object reference not set to an instance of an object.]
var folderID = (string)jResult["odata.context"]["odata.id"][0]["Id"];
First create a class for your json object
public class RootObject
{
[JsonProperty(PropertyName = "#odata.context")]
public string context { get; set; }
public List<Value> value { get; set; }
}
public class Value
{
[JsonProperty(PropertyName = "#odata.id")]
public string dataId { get; set; }
public string Id { get; set; }
public string DisplayName { get; set; }
public string ParentFolderId { get; set; }
public int ChildFolderCount { get; set; }
public int UnreadItemCount { get; set; }
public int TotalItemCount { get; set; }
}
Then Json Convert the Json string to your RootObject if your are using Newtonsoft Json then Deserilaze by using
RootObject shortiee = JsonConvert.DeserializeObject<RootObject>("Your Json String");
private List<string> GetDisplayNames(JObject content)
{
var obj = Json.Parse(content);
var values = obj["value"].ToList();
var displayNames = new List<string>();
foreach (var value in values)
{
displayNames .Add(system["DisplayName"].ToString());
}
return displayNames;
}
This would return the names, for example, and you could do this for each value you need to retrieve. However, this does not require you to serialize/deserialize the json object before using it. It works, but is most likely not best practice.
if (jResult["odata.error"] != null)
throw new Exception((string)jResult["odata.error"]["message"]["value"]);
//Attempt one - using dynamic [NOT WORKING - getting NULL values in the variables]
dynamic results = JsonConvert.DeserializeObject<dynamic>(content);
Side note: There is no key called "odata.error" in your JSON data. So you're effectively calling something which will return null.
One of the ways to deserialise JSON is to create model classes for the objects you want to process and deserialise into them directly, eg. JsonConvert.DeserializeObject<Folder>(content). As you are talking to an Office365 API, you find documentation and examples here on how they are defined.
Taken your folder response as an example, your model for a single Folder could look like this:
public class Folder
{
[JsonProperty(PropertyName = "#odata.id")]
public string OdataId { get; set; }
public string Id { get; set; }
public string DisplayName { get; set; }
public string ParentFolderId { get; set; }
public int ChildFolderCount { get; set; }
public int UnreadItemCount { get; set; }
public int TotalItemCount { get; set; }
}
Note1: in your example, you get a response with list of folders, so have to adjust this accordingly.
Note2: you can use JsonProperty to define a mapping between a JSON property/key and a C# property as shwon for #odata.id.
However, you can also use the Outlook Client Library which would make it mostly unnecessary to deal with JSON data directly (which seems preferable, unless you have a very specific reason to deal with JSON directly).

JSON Deserialize Error: Parameter cannot be null

Couldn't find an answer from the other Json Serialization issue questions, so maybe someone can help me:
I'm getting a JSON object from a REST api and attempting to Deserialize it to an object. Below is the JSON Object I receive:
{"id":"6wVcZ9ZF67ECUQ8xuIjFT2",
"userId":"83ca0ab5-3b7c-48fe-8019-000320081b00",
"authorizations":["employee","API","trainer","queueAdmin","supervisor","workflowAdmin","realtimeManager","forecastAnalyst","qualityEvaluator","contactCenterManager","teamLead","personnelAdmin","telephonyAdmin","qualityAdmin","businessAdmin","businessUser","accountAdmin","dialerAdmin","contentManagementUser","contentManagementAdmin","admin","api","scriptDesigner","agent","user"],
"primaryAuthorization":"employee",
"thirdPartyOrgName":"in",
"username":"somebody",
"selfUri":"https://blahblahblah.com/api/v1/auth/sessions/6wVcZ9ZF67ECUQ8xuIjFT2"}
And my object I'm attempting to DeSerialize to:
[Serializable]
public class Session : BaseRequest, ISession
{
public Session(string url) : base(url)
{
}
#region Members
[JsonProperty(PropertyName = "userId")]
public string UserId { get; set; }
[JsonProperty(PropertyName = "authorizations")]
public object[] Authorizations { get; set; }
[JsonProperty(PropertyName = "primaryAuthorization")]
public string PrimaryAuthorization { get; set; }
[JsonProperty(PropertyName = "thirdPartyOrgName")]
public string ThirdPartyOrgName { get; set; }
[JsonProperty(PropertyName = "username")]
public string Username { get; set; }
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "selfUri")]
public string SelfUri { get; set; }
#endregion
}
I simply make the web request and get the response stream using a stream reader and return the string. Pretty standard.
However, when I attempt to Deserialize into my Session object it always throws an error: Value Cannot be Null
var serializer = new JsonSerializer();
response = MakePostRequest(true);
var obj = serializer.Deserialize<Session>(new JsonTextReader(new StringReader(response)));
The response is the JSON string I get back from the web request and is exact to what I specified above.
I've done this before but normally I've been the one that designed the REST api. Not the case this time but I can't for the life of my figure out why this won't deserialize? I've specified the JSonProperty PropertyName to avoid issues with proper casing, is this not working right maybe? Any help is appreciated!
UDPATE
I think I found part of the problem. It is attempting to deserialize my base class which consists of :
public abstract class BaseRequest
{
protected BaseRequest(string apiUrl)
{
ApiUrl = apiUrl;
Request = (HttpWebRequest)WebRequest.Create(apiUrl);
}
public string ApiUrl { get; set; }
public string JsonPayload { get; set; }
public HttpWebRequest Request { get; private set; }
}
Is there any directive I can give to prevent it from doing so? Or will I need to refactor around this?
Below code works (using Json.Net):
var session = JsonConvert.DeserializeObject<Session>(json);
public class Session
{
public string Id { get; set; }
public string UserId { get; set; }
public List<string> Authorizations { get; set; }
public string PrimaryAuthorization { get; set; }
public string ThirdPartyOrgName { get; set; }
public string Username { get; set; }
public string SelfUri { get; set; }
}
EDIT
How should I tell it to ignore the base class?
var session = (Session)System.Runtime.Serialization.FormatterServices.GetSafeUninitializedObject(typeof(Session));
JsonConvert.PopulateObject(DATA, session);
But I don't think this is a nice way of doing it. Changing your design may be a better solution.
I've tested your code and it works fine, only change I made was removing the constructor, I take it that the serializer can't create an instance on the object for some reason, can you remove
public Session(string url) : base(url)
{
}
Your code works just fine for me but I haven't the BaseRequest source code so I made class with empty constructor.
IMO the exception is coming exactly from there. In the Session constructor the url parameter is null because your JSON object doesn't have url property. May be in the BaseRequest class you use this url param and you receive the Value Can't be Null error.
You can change just the name of parameter if this is the issue:
public Session(string selfUri ) : base(selfUri)
{
}
Check also if the 'response' variable is null. StringReader can throw this exception if you pass null to its constructor.

RESTSharp: Access values from deserialized class

I am using RESTSharp to receive and deserialize result from an API call. Response is JSON. I've created a class for the repsonse that looks like this:
public class JsonResponseClass
{
public class Selector
{
public static string verb { get; set; }
}
public class Points
{
public int definition { get; set; }
}
}
I do following to get the response:
var response = client.Execute<JsonResponseClass>(request);
var resData = response.Data;
How do I read/print values received from above? For example how do I print values verb and definition from the above deserialized response?
You're not supposed to nest the classes. Instead, add a property of each type to the root object's class.
public class JsonResponseClass
{
public Selector selector { get; set; }
public Points points { get; set; }
}
public class Selector
{
public static string verb { get; set; }
}
public class Points
{
public int definition { get; set; }
}
With that in place, the code works as expected:
var response = client.Execute<JsonResponseClass>(request);
var resData = response.Data;
var verb = resData.selector.verb;
var definition = resData.points.definition;
It's not clear what are you asking.
resData variable contains data from request stored in JsonResponseClass so you need to access it's fields like:
string verb = resData.verb;
Console.WriteLine(verb);

Create JSON object from c# class

I have a view model which looks like so:
public class CategoriesJsonViewModel
{
public int Id { get; set; }
public string Title { get; set; }
public List<Description> UsedDescriptions { get; set; }
public List<Description> UnusedDescriptions { get; set; }
}
I am creating a List of CategoriesJsonViewModel in my controller and trying to send it to the client browser in Json format. I use Json() method to do that:
List<CategoriesJsonViewModel> categoriesVM = new List<CategoriesJsonViewModel>();
List<Category> categories = repo.GetAllCategories();
foreach(var i in categories)
{
CategoriesJsonViewModel categoryVM = new CategoriesJsonViewModel();
categoryVM.Id = i.Id;
categoryVM.Title = i.Title;
categoriesVM.Add(categoryVM);
categoryVM.UsedDescriptions = repo.GetUsedDescriptions(i.Id);
categoryVM.UnusedDescriptions = repo.GetUnusedDescriptions(i.Id);
}
return Json(categoriesVM);
Although the categoriesVM object is being built properly, I do not get appropriate Json object from it for some reason. Why is it so?
I suggest you get the outputted json and put into jsonlint.com
That'll help you find out what is causing the json to be invalid. It may be something to do with your definition of the Description object as your CategoriesJsonViewModel looks like it should be ok.

Categories

Resources