Pass Nested Deserialized JSON from Controller to View - c#

After using HttpClient class to convert my JSON to a string and deserialize it with
var response = Res.Content.ReadAsStringAsync().Result;
data = JsonConvert.DeserializeObject<List<Employee>>(response);
How do I pass the data that I receive in the Controller from the call using the Model below to the View?
public class RuleType
{
public int Id { get; set; }
public string Description { get; set; }
public bool Inactive { get; set; }
}
public class RuleCategory
{
public int Id { get; set; }
public string Description { get; set; }
public bool Inactive { get; set; }
}
public class Employee
{
public string Description { get; set; }
public object EndDateTime { get; set; }
public int Id { get; set; }
public bool Inactive { get; set; }
public int RuleAction { get; set; }
public DateTime StartDateTime { get; set; }
public RuleType RuleType { get; set; }
public RuleCategory RuleCategory { get; set; }
}
Here is one object from the call
[
{
"Description": "Test Description",
"EndDateTime": null,
"Id": 1,
"Inactive": false,
"RuleAction": -2,
"StartDateTime": "2017-01-06T14:58:58Z",
"RuleType": {
"Id": 6,
"Description": "Test Description",
"Inactive": false
},
"RuleCategory": {
"Id": 1,
"Description": "Description",
"Inactive": false
}
}
]

Not sure if I'm missing something, but if you have an object you want to return to the view from the controller, you simply:
return View(viewModel); // in your case viewModel = 'data'

As others have said here already, you should be deserializing the JSON into a RootObject instead of an Employee like so:
var response = Res.Content.ReadAsStringAsync().Result;
var data = JsonConvert.DeserializeObject<List<RootObject>>(response);
You can then pass the model into the view using just:
return View(data)
You should also consider renaming RootObject into something more useful (such as employee?) as RootObject is not a very useful or descriptive name.

Related

How to display JSON data (nested) in C#

I am fetching an API that returns a JSON response like this:
{
"id": 161635,
"rev": 1,
"fields": {
"System.Url": "http://google.com",
"System.Type": "Bug",
"System.State": "New",
"System.AssignedTo": {
"displayName": "John Doe"
}
}
}
I want to display the id and everything inside fields.
This is my model:
public class WorkItemDetail {
public int id { get; set; }
public Dictionary<string, object> fields {get;set;}
}
Here is the problem, I can display the id and everything in fields except for some reason, I can't show displayName
Here is what I doing:
#WorkItemDetailResponse.id
#WorkItemDetailResponse.fields["System.WorkItemType"];
#WorkItemDetailResponse.fields["System.State"];
#WorkItemDetailResponse.fields["System.AssignedTo"];
#WorkItemDetailResponse.fields["System.AssignedTo"]["displayName"]; <!-- does not work -->
#code{
WorkItemDetailResponse = JsonConvert.DeserializeObject<WorkItemDetail>(ResponseBody);
}
I am new to C# so I don't know why this line is not working
#WorkItemDetailResponse.fields["System.AssignedTo"]["displayName"]
Create your DTO structure as follows:
public class Fields
{
[JsonProperty("System.Url")]
public string SystemUrl { get; set; }
[JsonProperty("System.Type")]
public string SystemType { get; set; }
[JsonProperty("System.State")]
public string SystemState { get; set; }
[JsonProperty("System.AssignedTo")]
public SystemAssignedTo SystemAssignedTo { get; set; }
}
public class WorkItemDetail
{
public int id { get; set; }
public int rev { get; set; }
public Fields fields { get; set; }
}
public class SystemAssignedTo
{
public string displayName { get; set; }
}
here's fiddle: https://dotnetfiddle.net/F9Wppv
another way - using dynamic variable: https://dotnetfiddle.net/Goh7YY
You need to cast the object value to a JObject
((JObject)JsonConvert.DeserializeObject<WorkItemDetail>(json).fields["System.AssignedTo"])["displayName"]
JSON.Net will create a JObject if the property type is object and the value is a JSON object.
db<>fiddle

How to deserialize multidimensional JSON

I know people asked and already got some answers very similar question before like this, but still, I couldn't figure it out about mine. I have a JSON file contains a multidimensional object, like below:
{
"Common": {
"Required": "Required Entry ",
"Photos": "Photos",
"Videos": "Videos",
"Register": "Register"
},
"Forms": {
"Form": "Forms",
"Name": "Name",
"Phone": "Phone",
"Email": "Email",
"Message": "Message"
},
"Sections": {
"Home": {
"EventDateTime": "",
"MainTitle": "",
"SubTitle": ""
},
"About": {},
"Venue": {},
"Schedule": {},
"Speakers": {},
"Sponsors": {},
"Price": {},
"Contact": {}
}
}
I would like to deserialize it into my view model (LanguagesViewModel) like this:
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class LanguagesViewModel
{
public Common Common { get; set; }
public Buttons Buttons { get; set; }
public Forms Forms { get; set; }
public Navbar Navbar { get; set; }
public Sections Sections { get; set; }
}
public class Common
{
public string Required { get; set; }
public string Photos { get; set; }
public string Videos { get; set; }
public string Register { get; set; }
}
public class Forms
{
public string Form { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public string Message { get; set; }
}
public class Sections
{
public Home Home { get; set; }
public About About { get; set; }
public Venue Venue { get; set; }
public Schedule Schedule { get; set; }
public Speakers Speakers { get; set; }
public Sponsors Sponsors { get; set; }
public Price Price { get; set; }
public Contact Contact { get; set; }
}
public class Home
{
public string EventDateTime { get; set; }
public string MainTitle { get; set; }
public string SubTitle { get; set; }
}
public class About
{
}
public class Venue
{
}
public class Schedule
{
}
public class Speakers
{
}
public class Sponsors
{
}
public class Price
{
}
public class Contact
{
}
}
Some of the snippet to do this:
using (StreamReader sr = new StreamReader(language_file_path))
{
string contents = sr.ReadToEnd();
items = JsonConvert.DeserializeObject<LanguagesViewModel>(contents);
}
Somehow, I only can get the first level of the objects, which is:
LanguagesViewModel{
Common:null,
Forms:null,
Sections:null
}
Not the second level, not the third level. Did I do something wrong or have I missed something? Very appreciated for any kind of help.
Thank you.
You can Use this static class
public static class JsonHelper
{
public static T ToObject<T>(this string content)
{
var obj = JObject.Parse(content).GetValue(typeof(T).Name);
if (obj == null)
throw new NullReferenceException();
else
return obj.ToObject<T>();
//This ToObject here is default method written in object
}
}
Usage
var mymodel= json.ToObject<Forms>();
Or create a JSON object and read it with magic strings.
//Creating your JSON object
JObject content = JObject.Parse(sr.ReadToEnd()//or your json);
//content["your object name"] let you access to you object
var common =(Common)content["Common"];
in multidimensional objects, you can access them like this.
//content["level1"]["level2"]["level3"] & ...
var sections= (Home)content["Sections"]["Home"];
Also this way may work but i prefer the way with magic strings.
dynamic jsonObject = new JObject.Parse(sr.ReadToEnd());
var common = jsonObject.Common;
You can find more in this link
I hope this Helps!

Invalid class property declaration for json mapping

I have below json received from mailgun API.
{
"items": [{
"delivery-status": {
"message": null,
"code": 605,
"description": "Not delivering to previously bounced address",
"session-seconds": 0
},
"event": "failed",
"log-level": "error",
"recipient": "test#test.com"
},
{
//some other properties of above types
}]
}
Now I was trying to create a class structure for above json to auto-map the properties after deserializing.
public class test
{
public List<Item> items { get; set; }
}
public class Item
{
public string recipient { get; set; }
public string #event { get; set; }
public DeliveryStatus delivery_status { get; set; }
}
public class DeliveryStatus
{
public string description { get; set; }
}
This is how I deserialize and try to map the properties.
var resp = client.Execute(request);
var json = new JavaScriptSerializer();
var content = json.Deserialize<Dictionary<string, object>>(resp.Content);
test testContent = (test)json.Deserialize(resp.Content, typeof(test));
var eventType = testContent.items[0].#event;
var desc = testContent.items[0].delivery_status.description; //stays null
Now in the above class Item, recipient and #event gets mapped properly and since it was a keyword I was suppose to use preceding # character and it works well. But the delivery-status property from json, does not get mapped with delevery_status property in class DeliveryStatus. I have tried creating it as deliveryStatus or #deliver-status. The earlier on doesn't map again and the later one throws compile time exception. Is there anyway these things can be handled, like declaring a property with - in between? I cannot change response json as it is not getting generated from my end. Hoping for some help.
Update
Changed the class as below referring this answer, but did not help. Its null again.
public class Item
{
public string #event { get; set; }
[JsonProperty(PropertyName = "delivery-status")]
public DeliveryStatus deliveryStatus { get; set; }
}
I am not sure what the issue is at your end, but at least it works if you use this code. Make sure to include a recent version of Newtonsoft.Json in your project and you should be fine.
public class DeliveryStatus
{
public object message { get; set; }
public int code { get; set; }
public string description { get; set; }
[JsonProperty("session-seconds")]
public int session_seconds { get; set; }
}
public class Item
{
[JsonProperty("delivery-status")]
public DeliveryStatus delivery_status { get; set; }
public string #event { get; set; }
[JsonProperty("log-level")]
public string log_level { get; set; }
public string recipient { get; set; }
}
public class RootObject
{
public List<Item> items { get; set; }
}
public static void Main(string[] args)
{
string json = #"{
""items"": [{
""delivery-status"": {
""message"": null,
""code"": 605,
""description"": ""Not delivering to previously bounced address"",
""session-seconds"": 0
},
""event"": ""failed"",
""log-level"": ""error"",
""recipient"": ""test#test.com""
}]
}";
RootObject r = JsonConvert.DeserializeObject<RootObject>(json);
}

facebook graph api deserialization for page search

I'm using Facebook graph API to search pages, https://graph.facebook.com/search?q=platform&type=page
Here is the response in json, i've included only one:
{
"data": [
{
"category": "Media/news/publishing",
"category_list": [
{
"id": "108366235907857",
"name": "Newspaper"
}
],
"name": "Arab News",
"id": "10250877124"
}
],
"paging": {
"next": "https://graph.facebook.com/search?limit=1&offset=1&type=page&q=media&__after_id=10250877124"
}
}
Now, here are my classes in C#:
public class CategoryList
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}
public class DataRoot
{
[JsonProperty("category")]
public string Category { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("category_list")]
public CategoryList[] CategoryList { get; set; }
}
public class Paging
{
[JsonProperty("next")]
public string Next { get; set; }
}
public class FacebookPageResults
{
[JsonProperty("data")]
public DataRoot[] Data { get; set; }
[JsonProperty("paging")]
public Paging Paging { get; set; }
}
Here is the odd thing, when i try to deserialize it
FacebookPageResults response = new JavaScriptSerializer().Deserialize<FacebookPageResults>(res); , the CategoryList is always null, doesn't even fill up. I have tried with List CategoryList {get; set;} but the result is the same?
Any help or workaround about thi
If anyone is wondering, i found the solution:
FacebookPageResults response = JsonConvert.DeserializeObject(res);
This works
FacebookPageResults response = JsonConvert.DeserializeObject(res.ToString());

How can you deserialize JSON data in C# (using DataContractJsonSerializer) without knowing all property names?

I have been using the DataContractJsonSerializer to convert data returned from the HubSpot API into strongly-typed objects, but I'm having some trouble with the user profile object.
In this example, I am able to get the Id and IsContact properties, but can't figure out how to get the list of properties since I don't know in advance what those can be. I would like to make Properties a Dictionary but I'm not sure how to do this. I don't care about the versions for each property, just the value.
This is a simplified example of the data that is returned by the API:
{
"vid": 72361,
"is-contact": true,
"properties": {
"city": {
"value": "Burlington",
"versions": [
{
"value": "Burlington",
"source-type": "SALESFORCE",
"source-id": "continuous",
"source-label": null,
"timestamp": 1384319976006,
"selected": false
}
]
},
"country": {
"value": "US",
"versions": [
{
"value": "US",
"source-type": "SALESFORCE",
"source-id": "continuous",
"source-label": null,
"timestamp": 1384319976006,
"selected": false
}
]
},
"company": {
"value": "Bridgeline Digital",
"versions": [
{
"value": "Bridgeline Digital",
"source-type": "SALESFORCE",
"source-id": "continuous",
"source-label": null,
"timestamp": 1384319976006,
"selected": false
}
]
}
}
}
This is the object I am trying to deserialize to:
[DataContract]
public class HubSpotUserProfile
{
[DataMember(Name = "vid")]
public int Id { get; set; }
[DataMember(Name = "is-contact")]
public bool IsContact { get; set; }
[DataMember(Name = "redirect")]
public string RedirectUrl { get; set; }
[DataMember(Name = "properties")]
public Dictionary<string, HubSpotUserProfileProperty> Properties { get; set; }
}
[DataContract]
public class HubSpotUserProfileProperty
{
[DataMember(Name = "value")]
public string Value { get; set; }
}
I call this method to perform the deserialization:
public static T Post<T>(string url, string postData) where T : class
{
string json = Post(url, postData);
if (!String.IsNullOrWhiteSpace(json))
{
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
return (T)serializer.ReadObject(stream);
}
}
return null;
}
When I do this, no error is thrown, but Properties always has a Count of 0. Any idea on how I can accomplish this goal?
Use JsonObject type for your Properties property. In some very strange case DataContractJsonSerializer doesn't support Dictionary<> type in this case
If JSON.NET is an option then James has recently added ExtensionData support. See http://james.newtonking.com/archive/2013/05/08/json-net-5-0-release-5-defaultsettings-and-extension-data.
public class DirectoryAccount
{
// normal deserialization
public string DisplayName { get; set; }
// these properties are set in OnDeserialized
public string UserName { get; set; }
public string Domain { get; set; }
[JsonExtensionData]
private IDictionary<string, JToken> _additionalData;
[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
// SAMAccountName is not deserialized to any property
// and so it is added to the extension data dictionary
string samAccountName = (string)_additionalData["SAMAccountName"];
Domain = samAccountName.Split('\\')[0];
UserName = samAccountName.Split('\\')[1];
}
}
Depending on your chosen package for deserializing objects, your current models will work. We use JSon.Net for this exact purpose with HubSpot.
Here's samples of what we use...
[DataContract]
public class ContactHubSpotModel {
// snip for brevity
[DataMember(Name = "properties")]
public Dictionary<string, ContactProperty> Properties { get; set; }
}
[DataContract]
public class ContactProperty
{
[DataMember(Name = "value")]
public string Value { get; set; }
[DataMember(Name = "versions")]
List<ContactPropertyVersion> Versions { get; set; }
}
[DataContract]
public class ContactPropertyVersion
{
[DataMember(Name = "value")]
public string Value { get; set; }
[DataMember(Name = "source-type")]
public string SourceType { get; set; }
[DataMember(Name = "source-id")]
public string SourceId { get; set; }
[DataMember(Name = "source-label")]
public string SourceLabel { get; set; }
[DataMember(Name = "timestamp")]
public long Timestamp { get; set; }
[DataMember(Name = "selected")]
public bool Selected { get; set; }
}
Then you can dump a copy of your contact output into a file for validation like so...
string contactJson = GetContactString(); // pulls sample data stored in a .txt
ContactHubSpotModel contactModel = JsonConvert.DeserializeObject<ContactHubSpotModel>(contactJson);

Categories

Resources