What is JSON?
JSON (JavaScript Object Notation) is a lightweight data interchange format. It is based on a subset of JavaScript (standard ECMA-262 3rd edition-december 1999). JSON takes a completely language-independent text format, but also uses a similar idiom to the C language family (c, C + +, C #, Java, JavaScript, Perl, Python, etc.). These features make JSON an ideal data exchange language. Easy to read and write, but also easy to machine parse and generate (network transfer speed).
Why use JSON?
Let's look at a simple example, assuming that the client needs to request data from the server side:
Data if it is a simple object, such as an instance of a custom class user
Packagecom.example.hixin; Public classuser{PrivateString Shenfennum; PrivateString name; PrivateString Regtime; PrivateString address; PrivateString birthdate; PublicUser () {} PublicString Getshenfennum () {returnShenfennum; } Public voidsetshenfennum (String shenfennum) { This. Shenfennum =Shenfennum; } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } PublicString Getregtime () {returnRegtime; } Public voidsetregtime (String regtime) { This. Regtime =Regtime; } PublicString getaddress () {returnaddress; } Public voidsetaddress (String address) { This. Address =address; } PublicString getbirthdate () {returnbirthdate; } Public voidsetbirthdate (String birthdate) { This. Birthdate =birthdate; } @Override PublicString toString () {//TODO auto-generated Method Stub return"User [shenfennum=" + Shenfennum + ", name=" + name + ", regtime=" + Regtime + ", address=" + address + ", birthdate=" + b Irthdate + "]"; } }
You can use ObjectOutputStream when you send it, and use ObjectInputStream when you accept it. But this direct sending object
The way, although convenient, but in the use of the time prone to problems, for arraylist<user> This compound object is basically can not be considered!
Let's look at a more complex scenario:
There is a need for the device to pull all users who use this device from the service after verifying that the login is successful, and the server sends two types of data during the process.
1, Login Successful response: Can be an integer number, or it can be a string "success"
2, the use of the device all users:arraylist<user>
The client accepts the data returned by the server, which is essentially a stream (InputStream), and how to parse the two data from a stream. Obviously the way to send objects directly is impossible to solve!
At this point, you can consider JSON.
The eighth of Android network programming--JSON for communication between Android and server