From XML to JSON
Under the common B/S architecture of current application development, we will encounter many scenarios that require front-end and back-end data transmission. In the process of this transmission, the format of the data transmission, whether the method is fast and convenient, and whether the writing method is simple and easy to learn, have all become problems for programmers to consider when developing.
In 1996, W3C (World Wide Web Consortium, World Wide Web Consortium) officially announced the XML1.0 standard,
XML adopts a standard format to provide a unified data description and data exchange standard for Web-based applications. Unlike HTML, which focuses on solving ": how to display files in the browser", XML is more focused on solving: "how to data Describe in a structured way".
(It should be noted that XML is not a programming language, but a cross-language data format.)
XML itself is not complicated, but after adding more than 20 standards such as DTD, XSD, XPath, XSLT, etc., formulated by W3C, this simple data exchange format has become more complicated. Whenever programmers encounter, they can only get big heads. I have been studying hard for more than half a month, and it is hard to say that I know everything.
At this time, another steam engine driving the advancement of technology was also ignited-Ajax technology became popular, reflecting the more and more disadvantages of XML that cannot be ignored. The realization of XML is based on the DOM tree, and the implementation details of DOM in various browsers are not the same. Therefore, the cross-browser compatibility of XML is not good. At this time, a new data load format is required to be integrated into the HTML page. To meet the requirements of Ajax.
Finally, in 2002, the eighth year after the birth of XML, Douglas Crockford began to use JSON, a lightweight data exchange format.
After the first JSON message was sent, what surprised people most was that this was not a brand new data format, it was JavaScript.
document.domain = 'fudco';parent.session.receive( { to: "session", do: "test", text: "Hello world" } )
And because the data content itself is JavaScript, no additional analysis is needed, and everything can be solved by using a JS compiler.
Because JSON is very simple, it quickly became popular in the web world and became the ECMA standard. Almost all programming languages have libraries for parsing JSON, and in JavaScript, we can directly use JSON because JavaScript has built-in JSON parsing. To turn a JavaScript object into JSON is to serialize this object into a string in JSON format so that it can be transmitted to other computers over the network. If we receive a string in JSON format, we only need to deserialize it into a JavaScript object, and then we can use this object directly in JavaScript.
Json serialization and deserialization
Just as a dish is prepared, it needs to be served on a plate to the customer, so does the data transmission between the front and back ends. The data is serialized into a binary data stream through a specified format, and then the content of the data stream is transformed into a corresponding data object through deserialization.
Data form and conversion method in JSON
In JSON, data has the following forms:
- Object: an unordered "key/value" in the format
- Array: used to set the numerical order, the format is such as
- String: any number of Unicode characters in the format
There are three ways to serialize and deserialize data:
- Use JavaScriptSerializer class
- Use DataContractJsonSerializer class
- Use JSON.NET class library
Take the JavaScriptSerializer class as an example,
//创建用户列表
List<UserInfo> userList = new List<UserInfo>();
userList.Add(new UserInfo() { ID = 1, Name = "张三", CreateTime = DateTime.Now });
userList.Add(new UserInfo() { ID = 2, Name = "李四", CreateTime = DateTime.Now });
userList.Add(new UserInfo() { ID = 2, Name = "王五" });
//创建一个JavaScriptSerializer对象
JavaScriptSerializer serializer = new JavaScriptSerializer();
//将用户列表序列化成JSON
string serializedResult = serializer.Serialize(userList);
//将JOSN反序列化成用户列表
List<UserInfo> deserializeResult = serializer.Deserialize<List<UserInfo>>(serializedResult);
Only need to call the corresponding method, you can directly realize the serialization of the data content.
Do you think it is over here, of course not. In practical applications, there is no difficulty in processing the data itself. The real problem that needs to be considered is the additional attributes and settings of the data itself. Take us as an example. The real demand of customers for JSON data transmission in pure front-end spreadsheets is that this piece of data needs to ensure the complete transmission of all visual content.
JSON data processing in pure front-end tables
When actually dealing with user needs, after setting the cell as shown in the figure below, the user will not only have numbers in the cell, but also encounter the cell’s own style, custom function, custom format, custom function mini-chart, Custom labels, and custom row filtering.
When we open the relevant code, we can clearly see that the cell settings in the format have been saved.
In this picture, we can see that different types of data content can complete the serialization and deserialization process. In the process of using custom serialization, check the relevant code. The core of processing serialization is the process of calling the toJSON function in the typeName field. For example, you can associate this type of name with the window object. When deserializing, call the getTypeFromString function to get the type name and construct the type instance object, and then call the fromJSON method on the type instance.
In addition, there are many other attribute content, the following are examples of other style settings:
Background picture:
//这个例子设置了backgroundImageLayout属性。
var style = new GC.Spread.Sheets.Style();
style.backColor = "lightgreen";
style.backgroundImage = "/css/images/quarter1.png";
style.backgroundImageLayout = GC.Spread.Sheets.ImageLayout.center;
activeSheet.setStyle(1,1,style,GC.Spread.Sheets.SheetArea.viewport);
Watermark settings:
//此示例设置水印的单元格填充。
var type = new GC.Spread.Sheets.Style();
type.watermark = "User name";
type.cellPadding = "20";
type.labelOptions = {alignment:GC.Spread.Sheets.LabelAlignment.topLeft, visibility: GC.Spread.Sheets.LabelVisibility.visible};
activeSheet.setStyle(0, 1, type);
activeSheet.getRange(0, -1, 1, -1, GC.Spread.Sheets.SheetArea.viewport).height(60);
activeSheet.getRange(-1, 1, -1, 1).width(150);
var combo = new GC.Spread.Sheets.CellTypes.ComboBox();
combo.items([{ text: "Oranges", value: "11k" }, { text: "Apples", value: "15k" }, { text: "Grape", value: "100k" }]);
combo.editorValueType(GC.Spread.Sheets.CellTypes.EditorValueType.text);
activeSheet.setCellType(2, 1, combo, GC.Spread.Sheets.SheetArea.viewport);
activeSheet.getCell(2, 1, GC.Spread.Sheets.SheetArea.viewport).watermark("ComboBox Cell Type").cellPadding('10 10 20 10');
activeSheet.getCell(2, 1, GC.Spread.Sheets.SheetArea.viewport).labelOptions({alignment: GC.Spread.Sheets.LabelAlignment.bottomCenter, foreColor: 'yellowgreen', font: 'bold 15px Arial'});
activeSheet.getRange(2, -1, 1, -1, GC.Spread.Sheets.SheetArea.viewport).height(60);
Theme font:
//这个例子使用了themeFont属性。
var style = new GC.Spread.Sheets.Style();
style.formatter = "0.000%";
style.themeFont = "Body";
activeSheet.setStyle(1,1,style,GC.Spread.Sheets.SheetArea.viewport);
activeSheet.getCell(1,1).value("11");
There are also many settings for cells. These styles can be completely saved and transmitted as json data, bringing the convenience of real table json data transmission.
Pay attention to the following issues during use:
- Set the complete type name string for the typeName field (if there is a namespace, it should also include the namespace).
- If the custom type has circular dependencies or you want to reduce the size of the JSON data, or you have other more advanced requirements, then your custom type needs to rewrite the toJSON and fromJSON methods.
- If the custom type is defined in a closure, in other words, you do not want to define the custom type on the window object, you need to override the getTypeFromString function to manually parse the type string.
Code example:
GC.Spread.Sheets.getTypeFromString = function(typeString) {
switch (typeString) {
case "MyFormatter":
return MyFormatter;
case "MyRowFilter":
return MyRowFilter;
default:
return oldFun.apply(this, arguments);
}
};
MyTag.prototype.toJSON = function() {
return {
typeName: this.typeName, //necessary
name: this.name,
age: this.age
};
};
MyTag.prototype.fromJSON = function(settings) {
if (settings.name !== undefined) {
this.name = settings.name;
}
if (settings.age !== undefined) {
this.age = settings.age;
}
};
Summarize
This article introduces the story of data transmission from XML to JSON in detail, as well as the working principle of json serialization and deserialization. At the same time, it shows you how to fully realize the data serialization and de-serialization of the entire content in the front-end spreadsheet. How to do serialization.
The follow-up will also bring you more interesting or serious content~
I think it's good, just like it and let's go.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。