Follow this link;
Year: 2022
Possible values of empty json
An empty string is not a valid json;
string json = "";
While an empty string is not valid JSON two quotes is valid JSON. This is an important distinction.
Which is to say a string that contains two quotes is not the same thing as an empty string.
string json = "{}";
string json = "[]";
Valid minimal JSON strings are
The empty object '{}'
The empty array '[]'
The string that is empty '""'
A number e.g. '123.4'
The boolean value true 'true'
The boolean value false 'false'
The null value 'null'
Resource
https://stackoverflow.com/questions/30621802/why-does-json-parse-fail-with-the-empty-string
Convert Json String to C# object
Let’s say we have this json string in Ajax post method;
let groupObject = '[{ "Key": "Commercial", "IsMember": "true" }, { "Key": "Corporate", "IsMember": "false" }, { "Key": "Consumer", "IsMember": "false" }]';
Make sure this is a valid json. We can use following web site for json validation;
We will create a user group class in .NET;
public class UGroupVM
{
public string? Key { get; set; }
public string? IsMember { get; set; }
}
We will user JSON Deserialization to get group object (try to use IList or List otherwise deserialization will fail because json is formatted as key/value pair);
var userGroup = JsonSerializer.Deserialize<List<UserGroupVM>>(groupObject);
For Newtonsoft, this is the syntax
var userAdGroup =
JsonConvert.DeserializeObject<List<UserGroupVM>>(groupObject);
An alternative is this;
JArray jarray = JArray.Parse(groupObject);
foreach (JObject jObject in jArray)
{
Console.WriteLine($"{(string)jObject["Key"]} -> {(string)jObject["IsMember"]}");
}
Ajax request other than Get and Post
Type setting in Ajax request is used to specify HTTP method that can be used to make remote calls. Many firewalls and application servers are configured to discard other kind of request except Get and Post.
If we want to use other HTTP methods, then we can make a POST request, but add the X-HTTP-Method-Override header; Setting it to the method we want to use, like this;
X-HTTP-Method-Override: PUT
This convention is widely supported by web application frameworks and is a common way of creating RESTful web applications.
You can learn more about this here;
https://en.wikipedia.org/wiki/Representational_state_transfer
See the “Setting Timeouts and Headers” section for detail of how to set a header on a jQuery Ajax request.
Throw exception on server side and handle in jQuery AJAX post call
XMLHttpRequest (XHR) objects are used to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing.
Here are some references;
https://stackoverflow.com/questions/377644/jquery-ajax-error-handling-show-custom-exception-messages