JSON ASP.NET Deserialization failing, getting null - c#

From Javascript I send my object via string like so, data is what facebook FQL query returns:
var propData = new Object();
propData.d = data;
var jString = JSON.stringify(propData);
$('#<%=Hidden1.ClientID%>').val(jString);
$('#UpdatePanelTrigger').click();
Then, I receive this string on server side, display this JSON string in a label (which looks ok to me) and try to Deserialize it, code below.
public class Friends
{
public IList<Dictionary<string,string>> data {get; set;}
}
protected void UpdateTrigger_Click(object sender, EventArgs e)
{
JSON_out.Text = Hidden1.Value;
Friends fbookFriends = new System.Web.Script.Serialization.JavaScriptDerializer().Deserialize<Friends>(JSON_out.Text);
obj_check.Text = new System.Web.Script.Serialization.JavaScriptSErializer().Serialize(fbookFriends);
//The result of above line is {"data":null}
}
I don't understand why Deserializer refuses to convert this string to JSON.
Any help, would be greatly appreciated.
I.N.
PS: If it helps, My JSON string received on server, looks like this:
{"d":[{"uid":"XXXXXXXX","name":"Bro Number1","pic_square":"https://fbcdn-profile-a.akamaihd.net/beautiful_avatar.jpg"},{"uid":"XXXXX2","name":...

To be able to deserialize your json string in question your Friends class should be something like that
public class Friend
{
public string uid { get; set; }
public string name { get; set; }
public string pic_square { get; set; }
}
public class Friends
{
public List<Friend> d { get; set; }
}
But your comments says you have some top level fields like data (//The result of above line is {"data":null})

Related

JsonConvert.DeserializeObject returns nulls

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

How do I access the "text" and "audio" objects inside of a deserialized json?

I have this code, which downloads a string from this api, and then deserializes it.
I have figured out how to access the "word" and "phonetic" objects, but how would I access the "audio" object inside of the "phonetics" array, or some of the objects inside of "meanings"? 1
private void Button1_Click(object sender, EventArgs e)
{
string result = "";
string link = ($"https://api.dictionaryapi.dev/api/v2/entries/en/hello");
var json = new WebClient().DownloadString(link);
var jsonDes = JsonConvert.DeserializeObject<List<DictionaryAPIResultData>>(json);
foreach (var data in jsonDes)
{
Console.WriteLine( data.phonetics);
}
}
public class DictionaryAPIResultData
{
[JsonProperty("word")]
internal string word { get; set; }
[JsonProperty("phonetics")]
internal List<string> phonetics { get; set; }
}
Hope someone can help!
The JSON object looks like this:
"phonetics":[{"text":"həˈləʊ","audio":"//ssl.gstatic.com/dictionary/static/sounds/20200429/hello--_gb_1.mp3"},{"text":"hɛˈləʊ"}]
so just add another class to represent it and change your deserialization class to
public class DictionaryAPIResultData
{
[JsonProperty("word")]
internal string word { get; set; }
[JsonProperty("phonetics")]
internal List<Phonetics> phonetics { get; set; }
}
public class Phonetics
{
public string text { get; set; }
public string audio { get; set; }
}
the JsonProperty attribute do you only need if your class property has an different name than the property insinde the json, or if you change it from lower to upper case
I first misread it so here is the answer if you wanna play the sound How to play .mp3 file from online resources in C#? ...

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

Turn string into json C#

I have this sample code that i am working with. The json is a result of the http post.
var json = #"{'user': {
'country':'US',
'email':'testapi#example.com',
'first_name':'Test',
'last_name':'API',
'phone':null,
'zip':null,
'login_url':'https://new.site.com/xlogin/12325/abd9832cd92'
}
}";
var jsonSerializer = new JavaScriptSerializer();
var itemsList = (IDictionary<string, object>)jsonSerializer.DeserializeObject(json);
var url = itemsList["user.login_url"];
On itemsList["user.login_url"] i am getting the following error:
The given key was not present in the dictionary.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.
Source Error:
Line 545: var jsonSerializer = new JavaScriptSerializer();
Line 546: var itemsList = (IDictionary<string, object>)jsonSerializer.DeserializeObject(json);
Line 547: var url = itemsList["user.login_url"];
Line 548: }
Line 549:
Am i doing something wrong here? How should i access the first name, last name and url etc from this object?
Alternately, how can i tie this result to a class that has following properties? I just need a pointer to a good resource.
public class User
{
public string Country { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public string Zip { get; set; }
public string LoginUrl { get; set; }
}
Thanks.
Well I really don't understand why u are using IDictionary to parse json object.
Use Newtonsoft.Json instead of jsonSerializer much more essay to use.
Go on http://json2csharp.com/ and generate your class to define you json (copy json and result is C# class).
Now tie your json to new RootObject not user:
using System;
using Newtonsoft.Json;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var json = #"{'user': {
'country':'US',
'email':'testapi#example.com',
'first_name':'Test',
'last_name':'API',
'phone':null,
'zip':null,
'login_url':'https://new.site.com/xlogin/12325/abd9832cd92'
}
}";
RootObject userObj = JsonConvert.DeserializeObject<RootObject>(json.ToString());
}
}
//generated with http://json2csharp.com/
public class User
{
public string country { get; set; }
public string email { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public object phone { get; set; }
public object zip { get; set; }
public string login_url { get; set; }
}
public class RootObject
{
public User user { get; set; }
}
}
"user.login_url" is the property path you'd expect to use in JavaScript ... try accessing the dictionary keys instead
var user = itemsList["user"] as IDictionary<string,object>;
var url = user["login_url"] as string;
itemsList["user"] contains a second Dictionary. So you can navigate down to the login_url variable using
var user = (IDictionary<string, object>)itemsList["user"];
var login_url = user["login_url"];
Try using http://json.net/ it will give you a Dictionary with the types you want..

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