Deserializing a simple list in a response - c#

I am doing something like this:
RestResponse<OTContentReply> response = (RestResponse<OTContentReply>)client.Execute<OTContentReply>(request);
where OTContentReplay is a very simple class containing 4 strings like so:
public class OTContentReply
{
public string url { get; set; }
public string embed { get; set; }
public string title { get; set; }
public string description { get; set; }
}
The response contains a number of OTContentReply nodes and my code above does place the first node in an instance of OTConentReply. (Great!)
What I want to do now is get all of the content nodes into an array or list. I tried this:
RestResponse<List<OTContentReply>> response = (RestResponse<List<OTContentReply>>)client.Execute<List<OTContentReply>>(request);
but get the error:
Cannot implicitly convert type 'RestSharp.RestResponse<System.Collections.Generic.List<Algoa.OpenTouchCtrl.OTContentReply>>' to 'RestSharp.RestResponse'
What is the proper way to do this?

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 to write correct json path?

I have a json object like that:
And i want to access the "question" field throught this code-line:
string msg = (json1["data"][0]["question"]).ToString();
But it doesnt work, why?
But it doesnt work, why?
Because you need to look at the json again.
"data" is an object, not an array. As such "[0]" is not valid as it would access the first element of the array. The only array you have in there is the "answers" element. "question" is directly a property of "data".
Prepare a C# Model like below
public class rootClass
{
public bool ok { get; set; }
public data data { get; set; }
}
public class data
{
public string question { get; set; }
public string[] answers { get; set; }
public int id { get; set; }
}
and use JsonConvert(Newtonsoft dll) class to deserialise and access like below
rootClass rootClass = JsonConvert.DeserializeObject<rootClass>(inputJson);
string msg = rootClass.data.question;

C# fix this Json deserialization type error?

I have a Json file in the following format:
"Adorable Kitten": {"layout": "normal","name": "Adorable Kitten","manaCost": "{W}","cmc": 1,"colors": ["White"],"type": "Host Creature — Cat","types": ["Host","Creature"],"subtypes": ["Cat"],"text": "When this creature enters the battlefield, roll a six-sided die. You gain life equal to the result.","power": "1","toughness": "1","imageName": "adorable kitten","colorIdentity": ["W"]}
and I am using the following code to put it into a list:
using (StreamReader r = new StreamReader(filepath))
{
string json = r.ReadToEnd();
List<Item> items = JsonConvert.DeserializeObject<List<Item>>(json);
textBox1.Text = items[0].name.ToString();
}
public class Item
{
public string layout;
public string name;
public string manaCost;
public string cmc;
public string[] colors;
public string type;
public string[] types;
public string[] subtypes;
public string text;
public string power;
public string toughness;
public string imageName;
public string[] colorIdentity;
}
Visual Studio is telling me that the "Adorable Kitten" part of the Json can not be deserialized. Normally I would get rid of that portion of the code but it is an excerpt from a file that is nearly 40000 lines long, so removing that for each item would be impractical. Additionally when i removed "Adorable Kitten" while troubleshooting I got a similar error for "layout". The error says that i need to either put it into a Json array or change the deserialized Type so that it is a normal .Net Type. Can anyone point what I'm doing wrong?
If your example is really what you are doing then you're simply deserializing to the wrong type.
Right now your code would work for the following:
[{"layout": "normal","name": "Adorable Kitten","manaCost": "{W}","cmc": 1,"colors": ["White"],"type": "Host Creature — Cat","types": ["Host","Creature"],"subtypes": ["Cat"],"text": "When this creature enters the battlefield, roll a six-sided die. You gain life equal to the result.","power": "1","toughness": "1","imageName": "adorable kitten","colorIdentity": ["W"]}]
Notice that it is a single JSON object inside a JSON array. This corresponds to the type you are deserializing to (List<Item>).
The example you posted of your JSON file isn't valid JSON (unless there are curly braces around the whole thing you left out) so you need to fix the file. If you really want there to be a list of Items in the JSON then wrapping everything in a single array will be the correct way to represent that.
First check if that the JSON you're receiving is a valid JSON, apparently the one you're receiving is wrong, you can check in https://jsonlint.com
Second create a model for the JSON, you can do it here http://json2csharp.com
public class AdorableKitten
{
public string layout { get; set; }
public string name { get; set; }
public string manaCost { get; set; }
public int cmc { get; set; }
public List<string> colors { get; set; }
public string type { get; set; }
public List<string> types { get; set; }
public List<string> subtypes { get; set; }
public string text { get; set; }
public string power { get; set; }
public string toughness { get; set; }
public string imageName { get; set; }
public List<string> colorIdentity { get; set;
}
}
Don't forget about the getters and setters on your model.

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

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