Transmission and parsing of JSON data under jquery (Asp.net MVC and Asp.net Api have different backend JSON receiving methods) JSON passing Mode Under Asp.net webapi jquery. Ajax cannot parse JSON

Source: Internet
Author: User
Tags javascript eval
Document directory
  • Asp.net webapi differences with MVC
  • Asp.net webapi differences with MVC

For more information, see Asp.net webapi's JSON value passing method.

I am entangled in a problem for a few days, and I want to help you.

A large amount of data is transmitted in JSON format on the network. JSON data transmission is lightweight, and data transmission using JSON solves two problems:
1. How to Handle JSON strings returned from the server;
2. How to submit JSON data to the server and parse JSON data on the server

Example 1:

(Asp.net mvc3.0 code, passing a few simple parameter values, using the MVC model binding method in the background to obtain the value)

 

 

 

Example 2:

(In the web API of Asp.net MVC 4.0, the code of knockout. js 2.0 is used, and the parameter is passed as a class, viewmodel. The formatters value passing method in the webapi is used. the backend uses the value from the request body and resolves the entire body as a (not multiple) object as a parameter, therefore, the background must define a category structure to match the complex data types sent from the foreground)

 

 

Example 3:

(For the web API under Asp.net MVC 4.0, the knockout. js 2.0 code is used to pass parameters as a custom type containing arrays. The formatters value passing method under the webapi is used)

Example 4:

(In Asp.net MVC 4.0, a common controller judges Ajax requests, transmits parameters as a spliced JSON string, and uses the formatters value passing method under webapi)

 

1) convert JS objects to JSON string format using the JSON. stringify Function

VaR bookinfo = new array ();

For (var I in self. Dates ()){
VaR Bi = {};
Bi ["datesnum"] = self. Dates () [I]. date;
Bi ["totalprice"] = self. Dates () [I]. date;
Bi ["stylistid"] = self. Dates () [I]. date;
Bookinfo. Push (BI );
}
VaR book = {
Book: bookinfo,
Name: "11 ",
};

VaR bookstring = JSON. stringify (book );

2) concatenate JSON strings

// This class is used to deserialize the JSON string of the Client

 

 

Brief Introduction to JSON

1. Introduction to JSON and its application scenarios

JSON is a data transmission protocol. You can also regard it as a data expression protocol. JSON is different from XML. JSON can only be used for data transmission, but not for document format.

JSON is JavaScript Object Natation. It is a lightweight data exchange format and is very suitable for server-to-JavaScript interaction. This article will quickly explain the JSON format and demonstrate how to process JSON format data on the client and server through code examples.

Although there are many ideas about how XML has the cross-platform and cross-language advantages, unless it is applied to Web Services, in common web applications, developers often use their brains for XML parsing. Whether the server generates or processes XML, or the client uses JavaScript to parse XML, it often leads to complicated code and extremely low development efficiency. In fact, for most web applications, they do not need complicated XML to transmit data at all, and XML scalability is rarely advantageous. Many Ajax applications even directly return HTML fragments to build dynamic web pages. Compared with returning XML and parsing it, returning HTML fragments greatly reduces the complexity of the system, but at the same time lacks some flexibility.

JSON provides another data exchange format for Web application developers. Let's take a look at what JSON is. JSON provides better simplicity and flexibility than XML or HTML fragments.

2. JSON syntax

Like XML, JSON is also based on plain text data format. Because JSON is designed for Javascript, The JSON data format is very simple. You can use JSON to transmit a simple string, number, or Boolean, or an array, or a complex object.

String, number, and Boolean are very simple in JSON format. For example, JSON represents a simple string "ABC" in the format:

"ABC"

In addition to the characters ", \,/and some control operators (\ B, \ f, \ n, \ r, \ t), other Unicode characters can be directly output.

Boolean Type: true or false. In addition, null in Javascript is expressed as null. Note that neither true, false, nor null has double quotation marks. Otherwise, it is considered as a string.

JSON can also represent an array object. [] is used to contain all elements. Each element is separated by commas. The element can be any value. For example, the following array contains a string, number, boolean and null:

["ABC", 12345, false, null]

The object is represented by a series of unordered key-value pairs in JSON. In fact, the object here is equivalent to the Map <string, Object> in Java, instead of Java class. Note that the key can only be represented by string.

For example, an address object contains the following key-value:

City: Beijing

Street: Chaoyang Road

Postcode: 100025 (integer)

JSON format:

{& Quot; City & quot;: & quot; Beijing & quot;, & quot; Street & quot;: & quot; Chaoyang Road & quot;, & quot; postcode & quot;: 100025}

Value can also be another object or array. Therefore, a complex object can be nested. For example, a person object contains the name and address objects, which can be expressed as follows:

{"Name": "Michael", "Address ":

{& Quot; City & quot;: & quot; Beijing & quot;, & quot; Street & quot;: & quot; Chaoyang Road & quot;, & quot; postcode & quot;: 100025}

}

 

FAQs about JSON format

1) jquery. Ajax cannot parse JSON objects. The cause and solution of invalid JSON error are reported.

We know that the JSON object caused by the invalid JSON error cannot be parsed. Generally, the syntax of the JSON string returned by the server is incorrect. In this case, we only need to carefully check the JSON to solve the problem.

Next let's talk about the problems encountered recently when using the $. Ajax () method in jquery 1.4 to parse JSON objects.

The JSON object is:

[{Name: 'Sale of second-hand houses ', infocount: 0, pageurl:'/ershoufang '}, {Name: 'Buy of second-hand houses', infocount: 0, pageurl: '/qiugou'}, {Name: 'second-hand house fit', infocount: 0, pageurl:'/esfzhuangxiu '}, {Name: 'second-hand recycling', infocount: 0, pageurl: '/huishou'}, {Name: 'Used motorcycle', infocount: 0, pageurl: '/motor'}, {Name: 'Used car purchase', infocount: 0, pageurl: '/ershoucheqg'}, {Name: 'second-hand car transfer', infocount: 9, pageurl:'/ershoe e '}, {Name: 'second-hand market', infocount: 0, pageurl: '/ershoushichang'}]

I wonder if you have found any problems with this JSON object. This method is correct in JS scripts and versions earlier than jquery 1.4. In versions 1.3 and earlier, jquery parses JSON objects using the Javascript eval method. In section 1.4, jquery uses a more rigorous method to parse JSON. All content must use double quotation marks.

As shown in jquery. parsejson (JSON), parsejson is interpreted as follows:

Accepts a JSON string and returns the parsed object.

Inputting a malformed JSON string throws an exception. For example, the following are malformed JSON strings:
{Test: 1} (test is not surrounded by double quotation marks)
{'Test': 1} (using single quotes instead of double quotes)

In addition, if you do not input anything, or an empty string, null, or undefined, parsejson will return null.

All strings must be expanded with double quotation marks. Numbers are null, true, and false.

From http://www.cnblogs.com/hyl8218/archive/2010/03/26/1694082.html

2) The input object is invalid and should be ":" or "}".

There is still a problem with the input JSON string format. special characters such as "quotation marks need to be encoded.

. Net background to obtain the front-end jquery ajax to pass the JSON array problem page script:
VaR people = [{"username": "T1", "password": "111111", "sex": "male" },{ "username": "T2 ", "password": "222222", "sex": "female"}];

I want to send this JSON script to the handler background after sending it.
$ ("# Btnsend"). BIND ("click", function (){
$. Post ("A. ashx", people, function (data, returnstatus) {}, "JSON ");
});

How should I accept it in the background? Generally, content. request ["parameter"] is accepted, but how can this be accepted by JSON arrays?

Solution 1: Go to www.json.org to download json2.js
Call JSON. stringify (jsondata) to convert the JSON object into a JSON string.
VaR people = [{"username": "T1", "password": "111111", "sex": "male" },{ "username": "T2 ", "password": "222222", "sex": "female"}];

Then construct a URL and send it back to the server:
$ ("# Btnsend"). BIND ("click", function (){
$. Post ("A. ashx", {XXXX: JSON. stringify (people)}, function (data, returnstatus) {}, "JSON ");
});

JSON string parsed by the server (pay attention to format issues)

How does the server parse the transmitted JSON data?

Reference description:

Asp.net webapi differences with MVC

Here are some differences between MVC and webapi's parameter binding:

  1. MVC only had model binders and no formatters. that's because MVC wocould model bind over the request's body (which it commonly expected to just be formurl encoded), whereas webapi uses a serializer over the request's body.
  2. MVC buffered the Request body, and so cocould easily feed it into model binding. webapi does not buffer the Request body, and so does not model bind against the request body by default.
  3. Webapi's binding can be determined entirely statically based off the action signature types. for example, in webapi, you know statically whether a parameter will bind against the body or the query string. whereas in MVC, the model binding system wocould search both body and query string.

 

The RC webapi parameter binder can be divided into two types:

 

1. Model binding

2. in formatters, model binding only takes values from the URL. This is different from the MVC model binding. formatters takes values from the request body, in addition, the whole body is parsed as a (not multiple) object as a parameter, and the background needs to define a corresponding class for the complex types passed by the foreground. The model binding system in MVC queries and matches the data in the body and querystring at the same time.

 

How can we choose webapi from these two methods?

 

1. by default, it is based on the parameter type. If the parameter is of the simple type (string, integer, floating point, time type, etc.), model binding is used, if it is a complex type (custom class, including one or more fields), use formatters

 

2. You can add the [frombody] attribute to the parameter, and then use formatters.

 

3. you can add the [modelbinder] attribute to the parameter and use model binding. This attribute allows you to specify a custom binder or use the [fromuri] attribute to use model binding.

 

4. Note that only one parameter in an action can use formatters. Otherwise, an exception will be thrown during runtime.

 

JSON. stringify

See http://technet.microsoft.com/zh-cn/sysinternals/cc836459 (V = vs.94)

Serialize a javascript value to JavaScript Object Notation (JSON) text.

JSON.stringify(value [, replacer] [, space])

JSON. parse function

Http://technet.microsoft.com/zh-cn/sysinternals/cc836466 (V = vs.94)

Generate the Javascript value representation (JSON) text from the JavaScript Object.

JSON.parse(text [, reviver])

 

Finally, a complete JSON data transmission instance is added.

Analysis of jquery Ajax JSON data transmission (Note: The model binding method under MVC is used)

From http://www.aichengxu.com/article/Javascript/664_7.html

 

 

Next let's talk about the problems encountered recently when using the $. Ajax () method in jquery 1.4 to parse JSON objects.

The JSON object is:

[{Name: 'Sale of second-hand houses ', infocount: 0, pageurl:'/ershoufang '}, {Name: 'Buy of second-hand houses', infocount: 0, pageurl: '/qiugou'}, {Name: 'second-hand house fit', infocount: 0, pageurl:'/esfzhuangxiu '}, {Name: 'second-hand recycling', infocount: 0, pageurl: '/huishou'}, {Name: 'Used motorcycle', infocount: 0, pageurl: '/motor'}, {Name: 'Used car purchase', infocount: 0, pageurl: '/ershoucheqg'}, {Name: 'second-hand car transfer', infocount: 9, pageurl:'/ershoe e '}, {Name: 'second-hand market', infocount: 0, pageurl: '/ershoushichang'}]

I wonder if you have found any problems with this JSON object. This method is correct in JS scripts and versions earlier than jquery 1.4. In versions 1.3 and earlier, jquery parses JSON objects using the Javascript eval method. In section 1.4, jquery uses a more rigorous method to parse JSON. All content must use double quotation marks.

As shown in jquery. parsejson (JSON), parsejson is interpreted as follows:

Accepts a JSON string and returns the parsed object.

Inputting a malformed JSON string throws an exception. For example, the following are malformed JSON strings:
{Test: 1} (test is not surrounded by double quotation marks)
{'Test': 1} (using single quotes instead of double quotes)

In addition, if you do not input anything, or an empty string, null, or undefined, parsejson will return null.

All strings must be expanded with double quotation marks. Numbers are null, true, and false.

From http://www.cnblogs.com/hyl8218/archive/2010/03/26/1694082.html

2) The input object is invalid and should be ":" or "}".

There is still a problem with the input JSON string format. special characters such as "quotation marks need to be encoded.

. Net background to obtain the front-end jquery ajax to pass the JSON array problem page script:
VaR people = [{"username": "T1", "password": "111111", "sex": "male" },{ "username": "T2 ", "password": "222222", "sex": "female"}];

I want to send this JSON script to the handler background after sending it.
$ ("# Btnsend"). BIND ("click", function (){
$. Post ("A. ashx", people, function (data, returnstatus) {}, "JSON ");
});

How should I accept it in the background? Generally, content. request ["parameter"] is accepted, but how can this be accepted by JSON arrays?

Solution 1: Go to www.json.org to download json2.js
Call JSON. stringify (jsondata) to convert the JSON object into a JSON string.
VaR people = [{"username": "T1", "password": "111111", "sex": "male" },{ "username": "T2 ", "password": "222222", "sex": "female"}];

Then construct a URL and send it back to the server:
$ ("# Btnsend"). BIND ("click", function (){
$. Post ("A. ashx", {XXXX: JSON. stringify (people)}, function (data, returnstatus) {}, "JSON ");
});

JSON string parsed by the server (pay attention to format issues)

How does the server parse the transmitted JSON data?

Reference description:

Asp.net webapi differences with MVC

Here are some differences between MVC and webapi's parameter binding:

  1. MVC only had model binders and no formatters. that's because MVC wocould model bind over the request's body (which it commonly expected to just be formurl encoded), whereas webapi uses a serializer over the request's body.
  2. MVC buffered the Request body, and so cocould easily feed it into model binding. webapi does not buffer the Request body, and so does not model bind against the request body by default.
  3. Webapi's binding can be determined entirely statically based off the action signature types. for example, in webapi, you know statically whether a parameter will bind against the body or the query string. whereas in MVC, the model binding system wocould search both body and query string.

 

The RC webapi parameter binder can be divided into two types:

 

1. Model binding

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.