JSON client-side and server-side format conversion_json
Here we will derive json from the syntax of javascript, and based on this, how to use JSON in ajax applications.
Everyone knows that there is Arrays in javascript: array. Its format is as follows:
var Beatles = ["Paul" ,"John","George","Ringo"];
The above example is in the form of an Array and is equivalent to the following:
var Beatles =new Array ["Paul","John","George","Ringo"];
The other one is Objects. The way to create objects is as follows:
var Beatles = {"Country":"England","YearFormed":1959,"Style":"Rock'n'Roll"}
The above creation method is the same Create as follows:
var Beatles = new Object( );
Beatles.Country = "England";
Beatles.YearFormad = 1959;
Beatles.Style = "Rock'n'Roll";
Same as other javascript objects Similarly, attributes can be represented by '.' or '[ ]'.
Object can contain Array, as follows:
var Beatles = {
"Country" :"England",
"YeatFormed": 1959,
"Style" : "Rock'n'Roll",
"Members":[ "Paul"," John","George","Ringo"]
}
You can also include Objects in Array:
var Rockbands =[
{
"Name":"BeatLes",
"County": "England" ,
"YearFormed" : 1959,
"Style" : "Rock'n'Roll" ,
"Members" : ["Paul","John","George","Ringo"]
},
{
"Name" ""Rolling Stones",
"Country":"England",
"YearFormed":1962,
"Style": "Rock' n'Roll",
"Members" :["Mick"],"Keith","Charlie","Bill"]
}
]
in JSON The official website describes JSON as follows:
1. A lightweight data conversion form
2. Easy for people to read and write.
3. Easy for machines to parse and generate.
JSON syntax. :
JSON may be difficult to read and write for some junior programmers, but it is still quite good for more experienced people (personal opinion)
Although the syntax of JSON and javascript are similar, each of them has similar syntax. An object cannot be assigned to a variable. That is, it is not an object but a string. We must use it through conversion every time we get JSON. Although the conversion can be achieved using the eval() function of JavaScript, for safety reasons. It is recommended that you use json.js for conversion. You can download it from the address provided above. The two most basic methods are:
JSON.parse(strJSON)-is used to convert JSON strings into JavaScript objects.
JSON.stringify(objJSON) – used to convert a JavaScript object into a JSON object.
This is data conversion on the client side, so how does it proceed on the server side? There are already very good conversion libraries for different languages. Because I am close to .net, here is how to use C# to perform server-side conversion of JSON.
I saw a foreign brother wrote a pretty good article on how to convert JSON under .net. It integrates JSON.NET and Microsoft's JavaScriptSerializer, so that no matter what format of JSON you have, you can basically handle it.
Now we provide a simple code for converting JSON, generating and parsing JSON:
public string Serialize(object value)
{
Type type = value.GetType();
Newtonsoft.Json.JsonSerializer json = new Newtonsoft.Json.JsonSerializer();
json.NullValueHandling = NullValueHandling.Ignore;
json.ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace;
json.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore;
json.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
if (type == typeof(DataRow))
json.Converters.Add(new DataRowConverter());
else if(type == typeof(DataTable))
json.Converters.Add(new DataTableConverter());
else if (type == typeof(DataSet))
json.Converters.Add(new DataSetConverter());
StringWriter sw = new StringWriter();
Newtonsoft.Json.JsonTextWriter writer = new JsonTextWriter(sw);
if (this.FormatJsonOutput)
writer.Formatting = Formatting.Indented;
else
writer.Formatting = Formatting.None;
writer.QuoteChar = '"';
json.Serialize(writer, value);
string output = sw.ToString();
writer.Close();
sw.Close();
return output;
}
public object Deserialize(string jsonText, Type valueType)
{
Newtonsoft.Json.JsonSerializer json = new Newtonsoft.Json.JsonSerializer();
json.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
json.ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace;
json.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore;
json.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
StringReader sr = new StringReader(jsonText);
Newtonsoft.Json.JsonTextReader reader = new JsonTextReader(sr);
object result = json.Deserialize(reader, valueType);
reader.Close();
return result;
}
在NET.JSON的基础上使用JavascriptSeriazible来转换:
internal class WebExtensionsJavaScriptSerializer : JSONSerializerBase, IJSONSerializer
{
public WebExtensionsJavaScriptSerializer(JSONSerializer serializer) : base(serializer)
{}
public string Serialize(object value)
{
JavaScriptSerializer ser = new JavaScriptSerializer();
List
if (value != null)
{
Type type = value.GetType();
if (type == typeof(DataTable) || type == typeof(DataRow) || type == typeof(DataSet))
{
converters.Add(new WebExtensionsDataRowConverter());
converters.Add(new WebExtensionsDataTableConverter());
converters.Add(new WebExtensionsDataSetConverter());
}
if (converters.Count > 0)
ser.RegisterConverters(converters);
}
return = ser.Serialize(value);
}
public object Deserialize(string jsonText, Type valueType)
{
// *** Have to use Reflection with a 'dynamic' non constant type instance
JavaScriptSerializer ser = new JavaScriptSerializer();
object result = ser.GetType()
.GetMethod("Deserialize")
.MakeGenericMethod(valueType)
.Invoke(ser, new object[1] { jsonText });
return result;
}
}
internal class WebExtensionsDataTableConverter : JavaScriptConverter
{
public override IEnumerable
{
get { return new Type[] {typeof (DataTable)}; }
}
public override object Deserialize(IDictionary
JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
下篇介绍如何在ASP.NET的环境下使用JSON和DataTable等的转换,还有介绍使用JQuery的AJAX调用Web Services的生成JSON、相当值得期待。^_^

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics


![VMware Horizon Client cannot be opened [Fix]](https://img.php.cn/upload/article/000/887/227/170835607042441.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
VMware Horizon Client helps you access virtual desktops conveniently. However, sometimes the virtual desktop infrastructure may experience startup issues. This article discusses the solutions you can take when the VMware Horizon client fails to start successfully. Why won't my VMware Horizon client open? When configuring VDI, if the VMWareHorizon client is not open, an error may occur. Please confirm that your IT administrator has provided the correct URL and credentials. If everything is fine, follow the solutions mentioned in this guide to resolve the issue. Fix VMWareHorizon Client Not Opening If VMW is not opening on your Windows computer
![VMware Horizon client freezes or stalls while connecting [Fix]](https://img.php.cn/upload/article/000/887/227/170942987315391.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
When connecting to a VDI using the VMWareHorizon client, we may encounter situations where the application freezes during authentication or the connection blocks. This article will explore this issue and provide ways to resolve this situation. When the VMWareHorizon client experiences freezing or connection issues, there are a few things you can do to resolve the issue. Fix VMWareHorizon client freezes or gets stuck while connecting If VMWareHorizon client freezes or fails to connect on Windows 11/10, do the below mentioned solutions: Check network connection Restart Horizon client Check Horizon server status Clear client cache Fix Ho

How to change picture format in win11? Everyone knows that image files come in many different formats, and each format has its own differences in image quality and file size. Moreover, when we use some image software for image processing, we will receive image formats due to compatibility. Limitation, we need to convert the image format, so how to perform this operation in win11 system? Many friends don’t know how to operate in detail. The editor has compiled the steps to format the C drive in win11 below. If you are interested, follow the editor to read below! Steps to modify win11 picture format 1. First, we can find the picture we need to modify the format on the win11 desktop. 2. At the end of the name of the picture we can

An exploration of communication between Vue and the server: Methods of handling timeout requests Introduction: During the development process of Vue, communicating with the back-end server is a very common situation. However, sometimes requests may time out due to network delays or other reasons. This article will discuss how to handle timeout requests in Vue and provide corresponding code examples. 1. Use Axios for requests In Vue, we usually use Axios as the HTTP client library to make network requests. Axios provides a series of methods to send requests and can

MQTT (MessageQueuingTelemetryTransport) is a lightweight message transmission protocol commonly used for communication between IoT devices. PHP is a commonly used server-side programming language that can be used to develop MQTT clients. This article will introduce how to use PHP to develop an MQTT client and include the following content: Basic concepts of the MQTT protocol Selection and usage examples of the PHPMQTT client library: Using the PHPMQTT client to publish and

How to use PHP to implement image resolution adjustment and format conversion Introduction: In website development, we often encounter the need to adjust image resolution and convert image formats. This article will introduce how to use PHP to implement these functions. Adjusting image resolution Adjusting image resolution can help us optimize page loading speed and reduce bandwidth consumption. The following is a sample code for adjusting image resolution using the PHPGD library: <?phpfunctionresizeImage($sourc

When many friends download files, they will first browse on the web page and then transfer to the client to download. But sometimes users will encounter the problem that the Baidu Netdisk webpage cannot start the client. In response to this problem, the editor has prepared a solution for you to solve the problem that the Baidu Netdisk webpage cannot start the client. Friends in need can refer to it. Solution: 1. Maybe Baidu Netdisk is not the latest version. Manually open the Baidu Netdisk client, click the settings button in the upper right corner, and then click version upgrade. If there is no update, the following prompt will appear. If there is an update, please follow the prompts to update. 2. The detection service program of Baidu Cloud Disk may be disabled. It is possible that we manually or use security software to automatically disable the detection service program of Baidu Cloud Disk. Please check it out

A mobile client refers to an application that runs on a smartphone and provides users with various functions and services in the form of a native client or a web client. Mobile clients can be divided into two forms: original clients and web clients. Native clients refer to applications written for specific operating systems using specific programming languages and development tools. The advantage of web clients is that they have good cross-platform compatibility. , can run on different devices without operating system restrictions, but compared to the native client, the performance and user experience of the web client may be reduced.
