JSON conversion of jayrock

Source: Internet
Author: User
Tags tojson

I. Introduction and Examples

Jayrock is an open-source lgpl software that implements JSON and JSON-RPC and supports Microsoft ASP. NET Framework.

JSON + jayrock + ASP. NET Quick Start: http://jayrock.berlios.de/#quick-start

Introduction to JavaScript Object Notation (JSON) in JavaScript and. net

Features:
Simple formatted data exchange
2. Easy reading and writing habits
3. Easy Machine Analysis and Operation
4. the eval () method can be used in JavaScript to conveniently read JSON data.
5. JSON-Supported languages: ActionScript, C, C #, ColdFusion, E, Java, JavaScript, ML, objective caml, Perl, PHP, Python, REBOL, Ruby, and Lua.

 

: Http://developer.berlios.de/project/showfiles.php? Group_id = 4638

Example:

 

Entity class user. CS:

Public class user
{
Public user ()
{
//
// Todo: add the constructor logic here
//
}

Private int ID;

Public int ID
{
Get {return ID ;}
Set {id = value ;}
}
Private string name;

Public string name
{
Get {return name ;}
Set {name = value ;}
}
Private datetime time;

Public datetime time
{
Get {return time ;}
Set {time = value ;}
}
Private double money;

Public double money
{
Get {return money ;}
Set {money = value ;}
}
Private string [] STR;

Public String [] Str
{
Get {return STR ;}
Set {STR = value ;}
}
}

 

Page background functions:

    • Convert an object to JSON:

User user = new user ();
User. ID = 1;
User. Name = "you ";
User. Money = 2.3;
User. Time = datetime. now;
User. Str = new string [] {"1", "2", "3 "};
Jayrock. JSON. jsontextwriter writer = new jayrock. JSON. jsontextwriter ();
Jayrock. JSON. Conversion. jsonconvert. Export (user, writer );
String STR = writer. tostring ();
// STR equals{"ID": 1, "name": "you", "Time": "2009-04-14t14: 29: 29.4375000 + 08: 00", "money": 2.3, "str": ["1", "2", "3"]}

 

    • Convert JSON to object:

String STR = "{\" ID \ ": 1, \" Name \ ": \" \ ", \" time \ ": \" 2009-04-13t22: 21: 11.6562500 + 08: 00 \ ", \" Money \ ": 2.3, \" str \ ": [\" 1 \ ", \" 2 \", \ "3 \"]} ";
User user = (User) jayrock. JSON. Conversion. jsonconvert. Import (typeof (user), STR );

    • Convert an array to JSON:

Jayrock. JSON. jsontextwriter writer = new jayrock. JSON. jsontextwriter ();
Writer. writestartarray ();
Writer. writestring ("1 ");
Writer. writestring ("");
Writer. writestring ("3 ");
Writer. writeendarray ();
String STR = writer. tostring (); // STR:["1", "A", "3"]

 

    • Convert an object to JSON:

Jayrock. JSON. jsontextwriter writer = new jayrock. JSON. jsontextwriter ();
Writer. writestartobject ();
Writer. writemember ("wid"); // attribute name
Writer. writenumber (11 );
Writer. writemember ("date"); // attribute name
Writer. writestring (datetime. Now. tostring ());
Writer. writeendobject ();
String STR = writer. tostring (); // STR:["1", "A", "3"]

    • JSON get attributes:

String STR = "{\" wid \ ": 11, \" date \ ": \" 14:02:42 \"}";
Jayrock. JSON. jsontextreader reader = new jayrock. JSON. jsontextreader (New stringreader (STR ));
While (reader. Read ())
{
If (reader. tokenclass = jsontokenclass. String | reader. tokenclass = jsontokenclass. Number)
{
This. label9.text = This. label9.text + "," + reader. text;
}
}
// Display: 14:02:42

 

Note:

{"ID": 1, "name": "you", "Time": "2009-04-14t14: 29: 29.4375000 + 08: 00", "money": 2.3, "str": ["1", "2", "3"]} The time string in the JSON format is as follows: "2009-04-14t14: 29: 29.4375000 + 08: 00 ", at the front end, parse the string as follows:

<SCRIPT type = "text/JavaScript" src = "JS/json2.js"> </SCRIPT> // reference a json js File

// "2009-04-13t22: 21: 11.6562500 + 08: 00" parse this type
Function getothertime (data)
{
VaR STR = data. Split (".") [0]. Replace (/T/g ,"");
VaR da = parsedate (STR );
Return da. getfullyear () + "year" + (DA. getmonth () + 1) + "month" + DA. getdate () + "day" + DA. gethours () + ":" + DA. getminutes () + ":" + DA. getseconds ();
}

/*
Parses string type into date type.
Parsedate ('1970-1-1 ') return new date (2006, 1)
Parsedate ('2006-1-1 ') return new date (, 1)
Parsedate ('1970-1-1 15:14:16 ') return new date (2006)
Parsedate ('2006-1-1 15:14:16 ') return new date );
Parsedate ('1970-1-1 15:14:16. 123') return new date (2006, 254, 254)
Parsedate ('2006-1-1 15:14:16. 100') return new date (254, 254)
Parsedate ('incorrect format') retrun null
*/
Function parsedate (STR ){
If (typeof STR = 'string '){
VaR Results = Str. Match (/^ * (\ D {4})-(\ D {1, 2})-(\ D {1, 2}) * $ /);
If (RESULTS & results. length> 3)
Return new date (parseint (results [1]), parseint (results [2])-1, parseint (results [3]);
Results = Str. match (/^ * (\ D {4})-(\ D {1, 2})-(\ D {1, 2}) + (\ D {1, 2 }) :( \ D {1, 2}) :( \ D {1, 2}) * $ /);
If (RESULTS & results. length> 6)
Return new date (parseint (results [1]), parseint (results [2])-1, parseint (results [3]), parseint (results [4]), parseint (results [5]), parseint (results [6]);
Results = Str. match (/^ * (\ D {4})-(\ D {1, 2})-(\ D {1, 2}) + (\ D {1, 2 }) :( \ D {1, 2}) :( \ D {1, 2 })\. (\ D {1, 9}) * $ /);
If (RESULTS & results. length> 7)
Return new date (parseint (results [1]), parseint (results [2])-1, parseint (results [3]), parseint (results [4]), parseint (results [5]), parseint (results [6]), parseint (results [7]);
}
Return NULL;
}

/*
Parses the date/string type into the string type.
If the string type is input, it is first parsed as the date type
Incorrect date. ''is returned''
If the time part is 0, only the date part is returned.
*/
Function formatdate (v ){
If (typeof v = 'string') V = parsedate (v );
If (V instanceof date ){
Var y = V. getfullyear ();
VaR M = V. getmonth () + 1;
VaR d = V. getdate ();
VaR H = V. gethours ();
VaR I = V. getminutes ();
VaR S = V. getseconds ();
VaR MS = V. getmilliseconds ();
If (MS> 0) return y + '-' + M + '-' + D + ''+ H + ':' + I + ':' + S + '. '+ MS;
If (h> 0 | I> 0 | S> 0) return y + '-' + M + '-' + D + ''+ H + ': '+ I +': '+ S;
Return y + '-' + M + '-' + D;
}
Return '';
}

 

 

Ii. Conversion between JSON and Classes

1. Convert JSON object to Model-- JS defines that the JSON object is passed to the background service class. After receiving the JSON object in the background, it is converted into a data model.

JSON object = {'kid': 1, 'indexdirectory': 'C: \ root '}

Conversion Method:

Kdgpointdata KPD = (Kdgpointdata) jsonconvert. Import ( Typeof (Kdgpointdata), jsonobject. tostring ());

 

Kdgpointdata is a data model class. To use a jsonconvert object, you must reference two dynamic link libraries (for the address, seeArticleAppendix), and add: Using jayrock. JSON. conversion;

The import () method has been reloaded five times. Here, we use the first parameter of the type you want to convert, and the second parameter is the result after the JSON object is converted to a string.

Note: JS objects are received in the background and all objects are received. That is to say, the preceding jsonobject is an object in the C # method class. After conversion, It is the model. In addition, the number of elements and the Case sensitivity of keys in jsonobject must be consistent with the attribute in the model.

2. Convert model to JSON object --This does not need to be changed. You can directly use model or model [] as the return type of the method. After receiving it in JS, define the corresponding jsonreader.

If you define Ext. Data. Store to use the proxy attribute and define the corresponding URL, jayrock has a method to convert the model into a JSON string:

String Temp = Jsonconvert. exporttostring (model );

Then, response. Write (temp); response. End (); request this URL to obtain JSON data.

3. Convert datatable to JSON object-- There are two ways to convert able to model or model [], then convert the data using the second method, or write a method to splice the JSON string:

/// <Summary> Converts a datatable two-dimensional table to a string in JSON format. </Summary>
/// <Param name = "tablesource"> Database query results </Param>
/// <Param name = "fields"> Field name to be added </Param>
/// <Returns> </returns>
Public String Datatabletojson (datatable tablesource, String [] Fields)
{
String Jsondata = " {'Totalcount ': " + Tablesource. Rows. Count + " , 'Root ':[ " ;

If (Tablesource. Rows. Count > 0 )
{
Foreach (Datarow row In Tablesource. Rows)
{
Jsondata + = " { " ;
For ( Int I = 0 ; I < Fields. length; I ++ )
Jsondata + = " ' " + Fields [I] + " ':' " + Row [fields [I] + " ', " ;
Jsondata = Jsondata. substring ( 0 , Jsondata. Length - 1 );
Jsondata + = " }, " ;
}
Jsondata = Jsondata. substring ( 0 , Jsondata. Length - 1 );
Jsondata + = " ]} " ;
}
Else
{
Jsondata + = " ]} " ;
}

ReturnJsondata;
}

The encapsulated format is {

Totalcount: 6,

Root :[

{'Id': 1, 'name': 'lily'}, {'id': 2, 'name': 'mark '}...

]

}

Usage: String temp = datatabletojson (DT, {"ID", "name "});

 

 

Iii. Introduction to json2.js

Javascript uses the third edition of the ecmascript language specification for standardization.
JSON is a subset of JavaScript object-oriented syntax. JSON is a subset of JavaScript, so it is used in this language.
VaR myjsonobject = {"bindings ":[
{"Ircevent": "PRIVMSG", "method": "newuri", "RegEx": "^ http ://.*"},
{"Ircevent": "PRIVMSG", "method": "deleteuri", "RegEx": "^ Delete .*"
{"Ircevent": "PRIVMSG", "method": "randomuri", "RegEx": "^ random .*"
]
};
In the preceding example, an object with a separate member "bindings" is created. This member contains three objects.
("Ircevent", "method", and "RegEx") array
Members can be retrieved by using the. Or subscript operator or the subscript operator.
Myjsonobject. bindings [0]. Method // "newuri"

1. Use the eval () function:

To convert JSON text to an object, you can convert the text to an object. You can use the eval () function to call the Javascript editor. Since JSON is a subset of JavaScript, the compiler will parse the text correctly and generate the object structure. The text must be enclosed in brackets to avoid syntax ambiguity in JavaScript.
VaR myobject = eval ('+ myjsontext + ')');
The eval function is very fast.
It can compile and execute any JavascriptProgramTherefore, security issues occur.
When using trusted and completeSource codeYou can use the eval function.
This makes it safer to use the JSON parser.
For Web applications that use XMLHttpRequest, communication between pages only allows the same source, so it can be trusted. However, this is not perfect.
If the server does not have strict JSON encoding or strict input verification, invalid JSON text including dangerous Scripts may be transmitted. The eval function executes malicious scripts. The JSON parser can prevent such events.
2. Use the JSON Parser:

2.1 JSON. parse ();

The JSON parse parser can only recognize JSON text and reject all scripts. The browser's JSON parser that provides local JSON support will be much faster than the eval function. It is expected that the ecmascript standard will support local JSON in the future.

Format:
var myobject = JSON. parse (myjsontext, reviver);
parameter: myjsontext, JSON format string to be parsed
optional parameter of reviver-function, called as the key and value of each level of the final result. Each value is replaced by the value of the replacement function. This can be used to change a common class to a pseudo-class instance, or to convert a date string to a date object.
mydata = JSON. parse (text, function (Key, value) {
var type;
If (Value & typeof value = 'object ') {
type = value. type;
If (typeof type = 'string' & typeof window [type] = 'function ') {
return New (window [type]) (value);
}< BR >}< br> return value;
});
2.2 JSON. stringify ();
JSON stringifier performs reverse operations to convert the Javascript data structure to JSON text. JSON does not support the number of loops
data structure. Therefore, be careful not to provide a circular structure for JSON stringifier.

Format: format:
VaR myjsontext = JSON. stringify (myobject, replacer );
Parameter: myobject: the JavaScript Object to be converted into a string.
Replacer. If the stringify function finds an object with the tojson method, it executes this method and returns the generated value. Such an object can determine its own JSON representation.
The stringifier method can carry an optional string array. These strings are used to select attributes included in JSON text.
The stringifier method can carry an optional replacer function. The tojson method of each value in the structure (if
If yes. It transmits each key and value as a parameter. Of course, the object must contain this key. The value is returned by stringified.
If no array or substitution function is provided, an optional substitution function is provided to ignore the integrated attributes. If you want all the inherited attributes, you can provide a simple replacement function:
VaR myjsontext = JSON. stringify (myobject, function (Key, value ){
Return value;
});
The value in JSON does not represent any content. Functions and undefined values are excluded.
Uncertain quantity will be replaced with null. To replace other values, you can use the replacer function as follows:
Function replacer (Key, value ){
If (typeof value = 'number '&&! Isfinite (value )){
Return string (value );
}
Return value;
}
Open SourceCodeJSON parser and JSON stringifier can be used. Minified can be smaller than 2.5 kb.

Http://www.json.org/json2.js

Http://www.crockford.com/javascript/jsmin.html

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.