I have Developed the C# Web Method. In this Method Request and Response are Json Array Format.
When I Read Json Array from Post Request, Error Occurred.
My Json Array is
[{"partner_hotel_code": "510","reservation_id": "7660"},{"partner_hotel_code": "510","reservation_id": "7666"}]
Error is
"Type 'System.Collections.Generic.IDictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' is not supported for deserialization of an array."
When i changed the Json into below mentioned format, My method is working Properly.
{"JsonData":[{"partner_hotel_code": "510","reservation_id": "7660"},{"partner_hotel_code": "510","reservation_id": "7666"}]}
But I don't want this format.
Please help, how to rectify the Problem.
You can map that JSON array to List of C# class.
public class RootObject
{
public string partner_hotel_code { get; set; }
public string reservation_id { get; set; }
}
In the web method add parameter List<RootObject> ObjectList
You are getting this error because the Json parameter is required to be an object of key-value pairs, that is:
{"JsonData":[{"partner_hotel_code": "510","reservation_id":
"7660"},{"partner_hotel_code": "510","reservation_id": "7666"}]}
{'Key': Value} => Key - JsonData, Value => array of items
With this in mind, you can make your models to match this structure as follows:
Prepare a model Item,
public class Item
{
public string partner_hotel_code { get; set; }
public string reservation_id { get; set; }
}
Then prepare a root 'Node' object that will take in a list of the items, let's call it Reservations:
public class Reservations
{
List<Item> JsonData { get; set; }
}
You can then deserialize as shown below:
var data = new JavaScriptSerializer().Deserialize<Reservations>(postData);
But the structure you wanted is something like: [{"partner_hotel_code": "510",...}]
You can achieve this by many ways, an example is using a foreach:
var list = new List<Item>();
foreach(var item in data.JsonData)
{
list.Add(item);
}
/*The value of list here will contain the items*/
listArray[] myArray = list.ToArray();
another solution to this problem is to serialize your array first, then create a JSON object with your method parameter name, and Serialize that...
it goes something like this
var myobj = { myArray: JSON.stringify(a) };
passedData = JSON.stringify(myobj);
$.ajax({
type: "POST", contentType: "application/json", data: passedData,
url: window.location.href + "/myMethod",
success: function (result) {
....
}
});
and the webMethod
public static void myMethod(String myArray)
{
dynamic jsonResponse = JsonConvert.DeserializeObject(myArray);
for (var i = 0; i < jsonResponse.Count; i++)
{
...........
}
}
I have a Web API service call that updates a user's preferences. Unfortunately when I call this POST method from a jQuery ajax call, the request parameter object's properties are always null (or default values), rather than what is passed in. If I call the same exact method using a REST client (I use Postman), it works beautifully. I cannot figure out what I'm doing wrong with this but am hoping someone has seen this before. It's fairly straightforward...
Here's my request object:
public class PreferenceRequest
{
[Required]
public int UserId;
public bool usePopups;
public bool useTheme;
public int recentCount;
public string[] detailsSections;
}
Here's my controller method in the UserController class:
public HttpResponseMessage Post([FromBody]PreferenceRequest request)
{
if (request.systemsUserId > 0)
{
TheRepository.UpdateUserPreferences(request.UserId, request.usePopups, request.useTheme,
request.recentCount, request.detailsSections);
return Request.CreateResponse(HttpStatusCode.OK, "Preferences Updated");
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.NotAcceptable, "You must provide User ID");
}
}
Here's my ajax call:
var request = {
UserId: userId,
usePopups: usePopups,
useTheme: useTheme,
recentCount: recentCount,
detailsSections: details
};
$.ajax({
type: "POST",
data: request,
url: "http://localhost:1111/service/User",
success: function (data) {
return callback(data);
},
error: function (error, statusText) {
return callback(error);
}
});
I've tried setting the dataType & contentType to several different things ('json', 'application/json', etc) but the properties of the request object are always defaulted or null. So, for example, if I pass in this object:
var request = {
UserId: 58576,
usePopups: false,
useTheme: true,
recentCount: 10,
detailsSections: ['addresses', 'aliases', 'arrests', 'events', 'classifications', 'custody', 'identifiers', 'phone', 'remarks', 'watches']
}
I can see a fully populated request object with the valid values as listed above. But in the Web API controller, the request is there, but the properties are as follows:
UserId: 0,
usePopups: false,
useTheme: false,
recentCount: 0,
detailsSections: null
FYI - I'm not doing ANY ASP.Net MVC or ASP.NET pages with this project, just using the Web API as a service and making all calls using jQuery $.ajax.
Any idea what I'm doing wrong here? Thanks!
UPDATE: I just want to note that I have many methods in this same Web API project in other controllers that do this exact same thing, and I am calling the exact same way, and they work flawlessly! I have spent the morning comparing the various calls, and there doesn't appear to be any difference in the method or the headers, and yet it just doesn't work on this particular method.
I've also tried switching to a Put method, but I get the exact same results - the request object comes in, but is not populated with the correct values. What's so frustrating is that I have about 20 controller classes in this project, and the Posts work in all of those...
This seems to be a common issue in regards to Asp.Net WebAPI.
Generally the cause of null objects is the deserialization of the json object into the C# object. Unfortunately, it is very difficult to debug - and hence find where your issue is.
I prefer just to send the full json as an object, and then deserialize manually. At least this way you get real errors instead of nulls.
If you change your method signature to accept an object, then use JsonConvert:
public HttpResponseMessage Post(Object model)
{
var jsonString = model.ToString();
PreferenceRequest result = JsonConvert.DeserializeObject<PreferenceRequest>(jsonString);
}
So there are 3 possible issues I'm aware of where the value does not bind:
no public parameterless constructor
properties are not public settable
there's a binding error, which results in a ModelState.Valid == false - typical issues are: non compatible value types (json object to string, non-guid, etc.)
So I'm considering if API calls should have a filter applied that would return an error if the binding results in an error!
Maybe it will help, I was having the same problem.
Everything was working well, and suddently, every properties was defaulted.
After some quick test, I found that it was the [Serializable] that was causing the problem :
public IHttpActionResult Post(MyComplexClass myTaskObject)
{
//MyTaskObject is not null, but every member are (the constructor get called).
}
and here was a snippet of my class :
[Serializable] <-- have to remove that [if it was added for any reason..]
public class MyComplexClass()
{
public MyComplexClass ()
{
..initiate my variables..
}
public string blabla {get;set;}
public int intTest {get;set;
}
I guess problem is that your controller is expecting content type of [FromBody],try changing your controller to
public HttpResponseMessage Post(PreferenceRequest request)
and ajax to
$.ajax({
type: "POST",
data: JSON.stringify(request);,
dataType: 'json',
contentType: "application/json",
url: "http://localhost:1111/service/User",
By the way creating model in javascript may not be best practice.
Using this technique posted by #blorkfish worked great:
public HttpResponseMessage Post(Object model)
{
var jsonString = model.ToString();
PreferenceRequest result = JsonConvert.DeserializeObject<PreferenceRequest>(jsonString);
}
I had a parameter object, which had a couple of native types and a couple more objects as properties. The objects had constructors marked internal and the JsonConvert.DeserializedObject call on the jsonString gave the error:
Unable to find a constructor to use for type ChildObjectB. A class
should either have a default constructor, one constructor with
arguments or a constructor marked with the JsonConstructor attribute.
I changed the constructors to public and it is now populating the parameter object when I replace the Object model parameter with the real object. Thanks!
I know, this is a bit late, but I just ran into the same issue. #blorkfish's answer worked for me as well, but led me to a different solution. One of the parts of my complex object lacked a parameter-less constructor. After adding this constructor, both Put and Post requests began working as expected.
I have also facing this issue and after many hours from debbug and research can notice the issue was not caused by Content-Type or Type $Ajax attributes, the issue was caused by NULL values on my JSON object, is a very rude issue since the POST neither makes but once fix the NULL values the POST was fine and natively cast to my respuestaComparacion class here the code:
JSON
respuestaComparacion: {
anioRegistro: NULL, --> cannot cast to BOOL
claveElector: NULL, --> cannot cast to BOOL
apellidoPaterno: true,
numeroEmisionCredencial: false,
nombre: true,
curp: NULL, --> cannot cast to BOOL
apellidoMaterno: true,
ocr: true
}
Controller
[Route("Similitud")]
[HttpPost]
[AllowAnonymous]
public IHttpActionResult SimilitudResult([FromBody] RespuestaComparacion req)
{
var nombre = req.nombre;
}
Class
public class RespuestaComparacion
{
public bool anioRegistro { get; set; }
public bool claveElector { get; set; }
public bool apellidoPaterno { get; set; }
public bool numeroEmisionCredencial { get; set; }
public bool nombre { get; set; }
public bool curp { get; set; }
public bool apellidoMaterno { get; set; }
public bool ocr { get; set; }
}
Hope this help.
I came across the same issue. The fix needed was to ensure that all serialize-able properties for your JSON to parameter class have get; set; methods explicitly defined. Don't rely on C# auto property syntax! Hope this gets fixed in later versions of asp.net.
A bit late to the party, but I had this same issue and the fix was declaring the contentType in your ajax call:
var settings = {
HelpText: $('#help-text').val(),
BranchId: $("#branch-select").val(),
Department: $('input[name=departmentRadios]:checked').val()
};
$.ajax({
url: 'http://localhost:25131/api/test/updatesettings',
type: 'POST',
data: JSON.stringify(settings),
contentType: "application/json;charset=utf-8",
success: function (data) {
alert('Success');
},
error: function (x, y, z) {
alert(x + '\n' + y + '\n' + z);
}
});
And your API controller can be set up like this:
[System.Web.Http.HttpPost]
public IHttpActionResult UpdateSettings([FromBody()] UserSettings settings)
{
//do stuff with your UserSettings object now
return Ok("Successfully updated settings");
}
In my case problem was solved when i added
get{}set{}
to parameters class definition:
public class PreferenceRequest
{
public int UserId;
public bool usePopups {get; set;}
public bool useTheme {get; set;}
public int recentCount {get; set;}
public string[] detailsSections {get;set;}
}
enstead of:
public class PreferenceRequest
{
[Required]
public int UserId;
public bool usePopups;
public bool useTheme;
public int recentCount;
public string[] detailsSections;
}
As this issue was troubling me for almost an entire working day yesterday, I want to add something that might assist others in the same situation.
I used Xamarin Studio to create my angular and web api project. During debugging the object would come through null sometimes and as a populated object other times. It is only when I started to debug my project in Visual Studio where my object was populated on every post request. This seem to be a problem when debugging in Xamarin Studio.
Please do try debugging in Visual Studio if you are running into this null parameter problem with another IDE.
Today, I've the same problem as yours. When I send POST request from ajax the controller receive empty object with Null and default property values.
The method is:
[HttpPost]
public async Task<IActionResult> SaveDrawing([FromBody]DrawingModel drawing)
{
try
{
await Task.Factory.StartNew(() =>
{
//Logic
});
return Ok();
}
catch(Exception e)
{
return BadRequest();
}
}
My Content-Type was correct and everything else was correct too. After trying many things I found that sending the object like this:
$.ajax({
url: '/DrawingBoard/SaveDrawing',
type: 'POST',
contentType: 'application/json',
data: dataToPost
}).done((response) => { });
Won't work, but sending it like this instead worked:
$.ajax({
url: '/DrawingBoard/SaveDrawing',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(dataToPost)
}).done((response) => { });
Yes, the missing JSON.stringify() caused the whole issue, and no need to put = or anything else as prefix or suffix to JSON.stringify.
After digging a little bit. I found that the format of the request payload completely different between the two requests
This is the request payload with JSON.stringify
And this is the request payload without JSON.stringify
And don't forget, when things get magical and you use Google Chrome to test your web application. Do Empty cache and hard reload from time to time.
I ran into the same issue, the solution for me was to make certain the types of my class attributes matched the json atributes, I mean
Json: "attribute": "true"
Should be treated as string and not as boolean, looks like if you have an issue like this all the attributes underneath the faulty attribute will default to null
I ran into the same problem today as well. After trying all of these, debugging the API from Azure and debugging the Xamarin Android app, it turns out it was a reference update issue. Remember to make sure that your API has the Newtonsoft.JSON NUGET package updated (if you are using that).
My issue was not solved by any of the other answers, so this solution is worth consideration:
I had the following DTO and controller method:
public class ProjectDetailedOverviewDto
{
public int PropertyPlanId { get; set; }
public int ProjectId { get; set; }
public string DetailedOverview { get; set; }
}
public JsonNetResult SaveDetailedOverview(ProjectDetailedOverviewDto detailedOverview) { ... }
Because my DTO had a property with the same name as the parameter (detailedOverview), the deserialiser got confused and was trying to populate the parameter with the string rather than the entire complex object.
The solution was to change the name of the controller method parameter to 'overview' so that the deserialiser knew I wasn't trying to access the property.
I face this problem this fix it to me
use attribute [JsonProperty("property name as in json request")]
in your model by nuget package newton
if you serializeobject call PostAsync only
like that
var json = JsonConvert.SerializeObject(yourobject);
var stringContent = new StringContent(json, UnicodeEncoding.UTF8, "application/json");
var response = await client.PostAsync ("apiURL", stringContent);
if not work remove [from body] from your api
HttpGet
public object Get([FromBody]object requestModel)
{
var jsonstring = JsonConvert.SerializeObject(requestModel);
RequestModel model = JsonConvert.DeserializeObject<RequestModel>(jsonstring);
}
public class CompanyRequestFilterData
{
public string companyName { get; set; }
public string addressPostTown { get; set; }
public string businessType { get; set; }
public string addressPostCode{ get; set; }
public bool companyNameEndWith{ get; set; }
public bool companyNameStartWith{ get; set; }
public string companyNumber{ get; set; }
public string companyStatus{ get; set; }
public string companyType{ get; set; }
public string countryOfOrigin{ get; set; }
public DateTime? endDate{ get; set; }
public DateTime? startDate { get; set; }
}
webapi controller
[HttpGet("[action]"),HttpPost("[action]")]
public async Task<IEnumerable<CompanyStatusVm>> GetCompanyRequestedData(CompanyRequestFilterData filter)
{}
jsvascript/typescript
export async function GetCompanyRequesteddata(config, payload, callback, errorcallback) {
await axios({
method: 'post',
url: hostV1 + 'companydata/GetCompanyRequestedData',
data: JSON.stringify(payload),
headers: {
'secret-key': 'mysecretkey',
'Content-Type': 'application/json'
}
})
.then(res => {
if (callback !== null) {
callback(res)
}
}).catch(err => {
if (errorcallback !== null) {
errorcallback(err);
}
})
}
this is the working one c# core 3.1
my case it was bool datatype while i have changed string to bool [companyNameEndWith] and [companyNameStartWith] it did work. so please check the datatypes.
I've got as simple asmx returning JSON:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class myWebService: System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public MyCustomClassObject GetTestData()
{
MyCustomClassObject x = new MyCustomClassObject();
x.PropertyA = "1";
x.PropertyC = "1";
return x;
}
c# class definition:
public class MyCustomClassObject
{
public string PropertyA { get; set; }
public string PropertyB { get; set; }
public string PropertyC { get; set; }
public object PropertyD { get; set; }
}
Called using jquery $.ajax:
var jqxhr = $.ajax(
{
type: 'POST',
contentType: "application/json; charset=utf-8",
url: "/WebServices/myWebService.asmx/GetTestData",
data: parameters,
dataType: "json",
success: successLoadingData,
error: errorLoadingData,
complete: function () { $("#LoadingImage").hide(); }
});
My JSON Response (with unwanted null values):
{"PropertyA":"1","PropertyB":null,"PropertyC":"1","PropertyD":null}
Question:
How do I only get the non null properties only in JSON using as much of what I have already as possible?
I've seen some answers on here where people are returning JSON objects and properties defined with JSON attributes but I'm simply returning my object and the webservice is converting it to JSON for me (due to the Response.Format attribute). If i have to I will change my approach but its my first JSON project so was hoping to keep it simple. Thanks.
Continuation from the comment section.
Even if you call a function to remove the null values, my personal opinion about it would be that it's bad design, having a dictionary and serializing that is a more elegant way than having to remove the properties we don't want after we're done.
What I would do is something like this:
public class MyCustomClassObject
{
public Dictionary<string, object> Foo { get; set; }
public MyCustomClassObject()
{
this.Foo = new Dictionary<string, object>();
}
}
public MyCustomClassObject GetTestData()
{
MyCustomClassObject x = new MyCustomClassObject();
x.Foo.Add("PropertyA", 2);
x.Foo.Add("PropertyC", "3");
return x.Foo;
}
this gives you a more generic object to work with and follows the JSON format better, since you theoretically could have a list or array of objects as a value, this is also more adaptable to work with since you can add the PropertyD here.
Why do you need something that removes the values after you've added them?
You can recursively remove the properties that are null, here's a snippet that does that:
function removeNulls(obj){
var res = {};
for(var key in obj){
if (obj[key] !== null && typeof obj[key] == "object")
res[key] = removeNulls(obj[key]);
else if(obj[key] !== null)
res[key] = obj[key];
}
return res;
};
The usage is removeNulls(jsonResult)
See it in action here
The following screen shot shows the data I'm sending (shown with firebug in firefox).
The code below then shows the method the ajax method calls. The Date and Id properties are correctly populated when hitting the server side method call but my array (of type CustomerRequests) has no values inside it, however the number of CustomerRequests in the post is correct.
Any ideas?
Thanks
My Controller method
public ActionResult Show(Customers request)
{
..
// Number of request.CustomerRequests is correct
// Although request.CustomerRequests[0].Name == null ?? which is wrong
Customers class below:
[DataContract]
public class Customers
{
[DataMember]
public CustomerRequests[] CustomerRequests{ get; set; }
[DataMember]
public DateTime Date { get; set; } // I can see this value
[DataMember]
public int Id{ get; set; } // I can see this value
}
[DataContract]
public class CustomerRequests
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string Expression { get; set; }
}
Javascript
$('textarea').each(function () {
var theName = 'The Name';
var theExpression = 'The Expression';
var obj = {
'Name': theName,
'Expression': theExpression
};
expressionArray.push(obj);
}); // close each
// val is the posted data
var val = {
'Id': '1',
'Date': '2013-10-10',
'CustomerRequests': $.makeArray(expressionArray)
};
I've tried although it doesn't work.
JSON.stringify({ Customers: val })
After all, we just have to add a content-type to your call and to remove the name from data.
It's something like
$.ajax({
url: '/controller/action',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(viewModel)
});
Please note that:
hard coding the URL is a bad practice. You should use #Url.Content("") or something like that
JSON.stringify may not work with older browsers. You may need to add this lib: http://www.json.org/js.html
Although this is not exactly an answer, because I have never used the built-in serializers, I can advise you to use the Json.NET library. I've been using it now for a long time, and I like it very much.
As for your question, I would try using List<T> instead of array, and I would probably try to instantiate the List in the constructor of the model. But these are just guesses, to be honest.
I have a Javascript object like this:
var jsonDataActual = {
"source": [{
"name": "testCaption0",
"desc": "testDescrip0",
"values": [{
"from": "/Date(1338811241074)/",
"to": "/Date(1346760041074)/",
"label": "testLabel0",
"customClass": "GanttRed"
}]
}],
"navigate": "scroll",
"scale": "weeks",
"maxScale": "months",
"minScale": "days",
"itemsPerPage": 11,
"onItemClick": function (data) { },
"onAddClick": function (dt, rowId) { }
};
it works fine for me. Now, because of my requirement and need, am making this entire object(including braces i.e.{ } and semicolon ;) as a string on server side (C#) and returning it to an ajax call (web Method) using a server side method:
in the server side method I do something like this:
return new JavaScriptSerializer().Serialize(jsonData);
but now this entire returned data (inside Success: function(msg){ var s=msg.d} ) is treated as string, hence it doesn't work.
I tried these:
1. var obj = eval('{' + msg.d +'}'); (removing beginning and ending braces in msg.d)
typeof(obj) is string. failed
2. eval('var obj ='+msg.d); (including beginning and ending braces in msg.d)
typeof(obj) is string. failed
3. var obj= jQuery.parseJson(msg.d);
typeof(obj) is string. failed
4. var obj = new Object();
//var obj = {};
obj=jQuery.parseJson(msg.d).
typeof(obj) is string. failed.
please help. How can I convert a server side returned json into object?
Why not is it working for me??. Is it because of structure of my json object??
and why does jsonDataActual works for me but not when sent as a string???
I saw this and this..
Please Help.....
found out solution to my specific problem.
I was constructing a string variable with my json data as its value. And then I would return this string to the client side function(the one making ajax request). i.e.
Server side method
[WebMethod]
public static string GetJsonData()
{
string jsonData = String.Empty;
foreach(var dataItem in objEntireData.Items)
{
// jsonData +=
}
return new JavaScriptSerializer().Serialize(result);
}
but it was not working. So instead of constructing a string variable and serializing it, I wrote a class with specific structure and sent it in the return statement(after serialzing).
i.e. see below classes
public class A
{
public A()
{
Values = new List<B>();
}
public string prop1 {get; set;}
public List<B> Values { get; set; }
}
public class B
{
public string prop2 { get; set; }
public string prop3 { get; set; }
}
and I would use this class as below:
[WebMethod]
public static string GetJsonData()
{
List<A> objA = new List<A>();
A objAItem = new A();
foreach (var dbItem in objDataBaseValues)
{
objA.prop1 = "test";
B objBItem = new B();
b.prop2="value";
b.prop3="value";
objA.Values.Add(objBItem);
}
return new JavaScriptSerializer().Serialize(objA);
}
wrapping up my entire data into a class structure and then serializing this worked for me. my client side function successfully recognized it as an object i.e.
$.ajax({
type: "POST",
url: "ProjectGanttChart.aspx/getData",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var jsonData = jQuery.parseJSON(msg.d);
populateGantt(jsonData);
}
});
try this
var json=(typeof msg.d) == 'string' ? eval('(' + msg.d + ')') : msg.d;
I've run into this many times before. When a WCF service is decrypting the returned data into JSON, string data will always have " " around it. You should always return objects, or lists of objects from your WCF service - even if these are custom objects created at your service level.
So, your service should be, say:
[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/Test?testId={testId}", RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
List<TestObjectJSON> Test(int testId);
This will then do the deserialization for you on the service side, without using the Serializer.
How can I convert a server side returned json into object?
You can use JSON.parse to do that.
Example:
a = [1, 2];
x = JSON.stringify(a); // "[1,2]"
o = JSON.parse(x); // [1, 2];