Read and Parse JSON data from POST request in C#
Solution 1
Convert your object to json string:
$.ajax({
type: 'POST',
url: "http://localhost:38504/DeviceService.ashx",
dataType: 'json',
data: JSON.stringify({
Username: 'Ali',
Age: 2,
Email: 'test'
}),
success: function (data) {
},
error: function (error) {
}
});
Solution 2
I am not sure why your datastring is encoded like an url (as it seems).
But this might solve the problem (altough i am not sure)
String data = new System.IO.StreamReader(context.Request.InputStream).ReadToEnd();
String fixedData = HttpServerUtility.UrlDecode(data);
User user = JsonConvert.DeserializeObject<User>(fixedData);
Ali Bassam
Peaceful Lebanese Citizen, Loves Computers and Technology, Programming and the Web. You can follow me here alibassam.com here twitter.com/alibassam_ and here.. on StackOverflow!
Updated on June 30, 2022Comments
-
Ali Bassam almost 2 years
I'm doing a POST request via JQuery's Ajax, with the type of data defined as
json
, containing the values to be posted to server, something likeUsername: "Ali"
.What I need to do in a Handler, is to read the values, deserialize them to an object named
User
.String data = new System.IO.StreamReader(context.Request.InputStream).ReadToEnd(); User user = JsonConvert.DeserializeObject<User>(data);
While debugging, the value of
data
is the following:Username=Ali&Age=2....
Now I'm sure this isn't
JSON
, so the next line would certainly produce an error:"Unexpected character encountered while parsing value: U. Path '', line 0, position 0."
What is the proper way to read
JSON
data from POST request?Client Side
$.ajax({ type: 'POST', url: "http://localhost:38504/DeviceService.ashx", dataType: 'json', data: { Username: 'Ali', Age: 2, Email: 'test' }, success: function (data) { }, error: function (error) { } });
-
Ashok Damani about 10 yearspost the string returning from that POST request.
-
Ali Bassam about 10 years@AshokDamani isn't it the value of
data
? -
Ali Bassam about 10 yearsWell this is a full String,
Username=Ali&Age=2&Email=test
, same things repeating... -
Luke about 10 yearslooks like your string is encoded like an url. Maybe if you pass it to an url decoder it might work (msdn.microsoft.com/de-de/library/6196h3wt%28v=vs.110%29.aspx)
-
Ali Bassam about 10 years@Luke I added the jQuery part.
-