Below is Json payload i am fetching from a API:
[
{
"id": "8c0e33ea-51af-44e0-8cb5-ef93703a4e6c",
"storeId": "xyz",
"name": "009DI",
"styleColors": []
},
{
"id": "f6284195-0f58-4f6b-a3b8-d5d22d1f7e63",
"storeId": "abc",
"name": "A001A",
"styleColors": []
}
]
Classes created for deserialization:
public class BINobjects
{
[JsonProperty(PropertyName = "binid")]
public string binid { get; set; }
[JsonProperty(PropertyName = "storeId")]
public string storeId { get; set; }
[JsonProperty(PropertyName = "binname")]
public string binname { get; set; }
}
public class BINdetails
{
[JsonProperty(PropertyName = "BINobjects")]
//public pages pages { get; set; }
public IList<BINobjects> BINobjects { get; set; }
}
Below is how I am trying to de-serialize it as a List of BINdetails objects
BINobjects BINdetails = JsonConvert.DeserializeObject<List<BINobjects>>(result);
Error:
cannot implicitly convert 'system.collections.generic.list to "tools.binobjects'. However, below code works but reading only 1 column from source.
var str = JsonConvert.DeserializeObject<List<BINobjects>>(result);
Is there a way to read directly into the object than into a variable. I am fine with whatever that works.
I got it fixed by editing the class property names:
public class BINobjects
{
[JsonProperty(PropertyName = "id")]
public string binid { get; set; }
[JsonProperty(PropertyName = "storeId")]
public string storeId { get; set; }
[JsonProperty(PropertyName = "name")]
public string binname { get; set; }
}
And then reading into variable:
var str = JsonConvert.DeserializeObject<List<BINobjects>>(result);
Related
First please start from picture i have attached the json output view. On picture you will see i was able to assign value only to the root level objects but on child level i failed to assign value properly which i need. My main goal is get output exactly like Json code bellow. How can i fix my controller to get exactly example json type output from JavaScriptSerializer?
Controller:
var root = new RootObject();
root.name = "Jan Kowalski";
root.email = "jan.kowalski#wp.pl";
root.dayOfCycle = "10";
//root.tags.Add(new Tag
//{
// tagId = "Xw",
//});
//root.scoring = 25;
//root.customFieldValues.Add(new CustomFieldValue
//{
// customFieldId = "n",
// //value = "white", value should be list
//});
root.ipAddress = "89.206.36.193";
var camp = new Campaign();
camp.campaignId = "jf7e3jn";
var jsBody = new JavaScriptSerializer().Serialize(root);
Model class:
public class Campaign
{
public string campaignId { get; set; }
}
public class Tag
{
public string tagId { get; set; }
}
public class CustomFieldValue
{
public string customFieldId { get; set; }
public List<string> value { get; set; }
}
public class RootObject
{
public string name { get; set; }
public string email { get; set; }
public string dayOfCycle { get; set; }
public Campaign campaign { get; set; }
public List<Tag> tags { get; set; }
public int scoring { get; set; }
public List<CustomFieldValue> customFieldValues { get; set; }
public string ipAddress { get; set; }
}
Json body i want from JavaScriptSerializer:
{
"name": "Jan Kowalski",
"email": "jan.kowalski#wp.pl",
"dayOfCycle": "10",
"campaign": {
"campaignId": "jf7e3jn"
},
"tags": [
{
"tagId": "Xw"
},
{
"tagId": "Nn"
}
],
"scoring": 25,
"customFieldValues": [
{
"customFieldId": "n",
"value": [
"white"
]
}
],
"ipAddress": "89.206.36.193"
}
As commented already, for the sake of completeness:
Missing: root.campaign = camp; just before creation of jsBody
Missing root.tags = new List<Tag>(); to prevent Null Reference Exception, just before root.tags.Add is executed
I am using http://plugins.krajee.com/file-input/demo in ASP .Net MVC 5 project, can you help me how I can generate initialPreview and initialPreviewConfig from server side?
public class ImgSetting
{
public string [] initialPreview { get; set; }
public ConfigSetting initialPreviewConfig { get; set; }
public string append { get; set; }
}
public class ConfigSetting
{
public string caption { get; set; }
public string width { get; set; }
public string url { get; set; }
public string key { get; set; }
public string [] extra { get; set; }
}
and I tried to make a JSON Array object:
ConfigSetting configSetting = new ConfigSetting();
configSetting.caption = file.FileName;
configSetting.width = "120px";
configSetting.url = "/localhost/avatar/delete";
configSetting.key = "100";
configSetting.extra = new string[] {id ="100" };
imgSetting.initialPreview = new string[] {"'<img src='~/Images/"+file.FileName +"' class='file-preview-image' alt='Desert' title='Desert'>'"};
imgSetting.initialPreviewConfig = configSetting;
imgSetting.append = "false";
string json = JsonConvert.SerializeObject(imgSetting);
return Json(json);
But it's still not working?
I am trying to list some data from a news section. I have two tables. News and NewsCategory
This is my model classes
public class News
{
public int NewsId { get; set; }
public string Name { get; set; }
public int NewsCategoryId { get; set; }
public virtual NewsCategory NewsCategory { get; set; }
}
public class NewsCategory
{
public int NewsCategoryId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual List<News> News { get; set; }
}
public class NewsDbContext : DbContext
{
protected override void OnConfiguring(DbContextOptions options)
{
options.UseSqlServer(Startup.Configuration.Get("Data:DefaultConnection:ConnectionString"));
}
public DbSet<News> News { get; set; }
public DbSet<NewsCategory> NewsCategory { get; set; }
}
This is also working, when I in my controller fect the data, with the exception of one thing. When I fect my news, I do not have a reference to my Category.
My controller code:
var news = _db.News.ToList();
This outputs :
[
{
"NewsId": 1,
"Name": "ghdfgd",
"NewsCategoryId": 1,
"NewsCategory": null
},
{
"NewsId": 2,
"Name": "gdfgdf",
"NewsCategoryId": 1,
"NewsCategory": null
}
]
As you can see, NewsCategory is empty. Although it is not:)
What am I missing?
It's because you are lazy loading the navigation properties.
Look into this article.
Just do this:
var news = _db.News.Include(n => n.NewsCategory).ToList();
I am getting json response from some server in format like:
[
{
"email":"john.doe#sendgrid.com",
"sg_event_id":"VzcPxPv7SdWvUugt-xKymw",
"sg_message_id":"142d9f3f351.7618.254f56.filter-147.22649.52A663508.0",
"timestamp":"1386636112",
"smtp-id":"<142d9f3f351.7618.254f56#sendgrid.com>",
"event":"processed",
"category":"category1",
"id": "001",
"purchase": "PO1452297845",
"Segmentid": "123456"
},
{
"email":"not an email address",
"smtp-id":"<4FB29F5D.5080404#sendgrid.com>",
"timestamp":"1386636115",
"reason":"Invalid",
"event":"dropped",
"category":"category2",
"id":"001",
"purchase":"PO1452297845",
"Segmentid":"123456"
},
{
"email":"john.doe#sendgrid.com",
"sg_event_id":"vZL1Dhx34srS-HkO-gTXBLg",
"sg_message_id":"142d9f3f351.7618.254f56.filter-147.22649.52A663508.0",
"timestamp":"1386636113",
"smtp-id":"<142d9f3f351.7618.254f56#sendgrid.com>",
"event":"delivered",
"category":"category1",
"id": "001",
"ip": "174.56.33.234",
"url": "http://www.google.com/",
"purchase": "PO1452297845",
"Segmentid":"123456"
}]
In mvc controller action I am getting these response via model like:
[ValidateInput(false)]
[HttpPost]
public async Task<ActionResult> Index(ResponseModel[] rec)
{
}
My model is like:
public class ResponseModel
{
public int ReportId { get; set; }
public string raw { get; set; }
public int event_post_timestamp { get; set; }
public string SegmentId { get; set; }
public string url { get; set; }
public string type { get; set; }
public string status { get; set; }
public string attempt { get; set; }
public string useragent { get; set; }
public string ip { get; set; }
public string reason { get; set; }
public string response { get; set; }
public string newsletter { get; set; }
public string category { get; set; }
public string sg_message_id { get; set; }
public string sg_event_id { get; set; }
[Column("smtp-id")]
[DataMember(Name="smtp-id")]
[JsonProperty("smtp-id")]
public string smtp_id { get; set; }
public string email { get; set; }
[Column("event")]
[JsonProperty("event")]
[DataMember(Name = "event")]
public string #event { get; set; }
public int timestamp { get; set; }
}
In action I am getting all property initialized but not smtp-id. So please suggest me how can I map response "smtp-id" attribute to my model.
Create your own ActionFilterAttribute similar to what was done here
I know this is a really old post but I came across this and found that there are two things needed.
[JsonProperty(PropertyName = "message-id")] using Newtonsoft.Json and
a simple 'custom' model binder https://stackoverflow.com/a/34030497/2455159
Then any Json data object in can be bound to a model/ viewmodel in a controller accepting posted data like a webhook, that has invalid (at least a '-' ) character in property names/ attributes.
I have an array nested in an object in a JSON string which I need deserialized at the server:
var orderStatus = {"auth": "xxxx", "resourceType": "order.status", "idSet": "2980", "lifecycleEvent": "modified", "objects": { "orders": [ { "id": "2980", "statusId": "6" } ] }
I use Robert Koritnik's plugin like this:
$.ajax({url: "receiveJson", type: "POST", data: $.toDictionary(orderStatus) });
My .net class file is:
public class orders
{
public string Id { get; set; }
public string statusId { get; set; }
}
public class objects
{
public orders orders { get; set; }
}
public class OrderStatus
{
public string clientName { get; set; }
public string source { get; set; }
public string auth { get; set; }
public string resourceType { get; set; }
public string idSet { get; set; }
public string lifecycleEvent { get; set; }
public objects objects { get; set; }
}
my controller code is:
public JsonResult receiveJson(OrderStatus orderStatus)
So the orders object is the array. It works up to creating orders as an object but id and status id in the orders object are null.
I have no control over the JSON I will receive, it has to be in this format.
I am new to JSON and .NET MVC. Don't know how to specify server side orders object as an array.
Fixed it by slightly amending my server side classes:
public class order
{
public string Id { get; set; }
public string statusId { get; set; }
}
public class objects
{
public List<order> orders { get; set; }
}
public class OrderStatus
{
public string clientName { get; set; }
public string source { get; set; }
public string auth { get; set; }
public string resourceType { get; set; }
public string idSet { get; set; }
public string lifecycleEvent { get; set; }
public objects objects { get; set; }
}
So the "orders" class has been changed to "order". "objects.orders" property is amended to be a list.
Now the jsondata is deserialized all the way down.