Android JSON for network data exchange

Source: Internet
Author: User

Android JSON for network data exchange
What is JSON (JavaScript Object Notation) is a lightweight data exchange format, which is easy to read and write, and easy to parse and generate by machines. It is very suitable for the interaction between servers and clients. JSON uses a text format unrelated to the programming language, but also uses the C-like language. These features make JSON an ideal data exchange format. 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, Boolean, or
An array or a complex Object. String, Number, and Boolean are very simple in JSON format. For example, JSON is used to represent a simple string.

"Abc" in the format of "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 a comma. The element can be any
Value. For example, the following array contains a String, Number, Boolean, and null:

["abc",12345,false,null]

In JSON, Object objects are represented by {} containing a series of unordered Key-Value pairs.
Object is equivalent to Map in Java Instead of Java Class. Note that the Key can only be a String table.
. For example, an Address object contains the following Key-Value:
City: Beijing
Street: Chaoyang Road
Postcode: 100025 (integer)
JSON format:

{"city":"Beijing","street":" Chaoyang Road ","postcode":100025}
Value can also be another Object or array. Therefore, a complex Object can be nested, for example,
The Person object contains the name and address objects, which can be expressed as follows:

{"name":"Michael","address": {"city":"Beijing","street":" Chaoyang Road ","postcode":100025}
 }


Below is an example: (remember to use the pilot package on the server side)

This is written on the code I wrote. Now I write down the main code.

Create a servlet:

Package cn. four. json; import java. io. IOException; import java. io. printWriter; import java. util. list; import javax. print. event. printServiceAttributeEvent; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import net. sf. json. JSONArray; import net. sf. json. JSONObject; import cn. four. service. foundservice; import cn. four. service. foundserviceImp; import cn. four. user. found; public class JSONDemoServlet extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {Foundservice fd = new FoundserviceImp (); // I wrote this before, inherited interface List
  
   
List = fd. getfound (); // new A listJSONObject jsb = new JSONObject (); // new A JSONObject jsb. put ("foundlist", list); // get the converted data JSONArray fdarray = jsb. getJSONArray ("foundlist"); // save it to the array response. setContentType ("text/plain"); // solves the garbled response. setCharacterEncoding ("UTF-8"); PrintWriter out = response. getWriter (); out. write (fdarray. toString (); // close out. flush (); out. close ();} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}}
  
The server end is over.

The following is an introduction to android

Android SDK provides the HttpClient class of Apache to process network access. I believe many readers and friends use it in other projects.
HttpClient. I wrote a method class to get the webpage content of a website. The Code is as follows:

Package com. four. http; import java. io. bufferedReader; import java. io. inputStreamReader; import org. apache. http. httpEntity; import org. apache. http. httpResponse; import org. apache. http. client. httpClient; import org. apache. http. client. methods. httpGet; import org. apache. http. impl. client. defaultHttpClient; import org. apache. http. params. httpConnectionParams; import org. apache. http. params. httpParams; public class h Ttpcontent {public String getContent (String url) throws Exception {StringBuilder sb = new StringBuilder (); HttpClient client = new DefaultHttpClient (); HttpParams httpParams = client. getParams (); // sets the network timeout parameter HttpConnectionParams. setConnectionTimeout (httpParams, 3000); HttpConnectionParams. setSoTimeout (httpParams, 5000); HttpResponse response = client.exe cute (new HttpGet (url); HttpEntity entity = respons E. getEntity (); if (entity! = Null) {BufferedReader reader = new BufferedReader (new InputStreamReader (entity. getContent (), "UTF-8"), 8192); String line = null; while (line = reader. readLine ())! = Null) {sb. append (line + "\ n") ;}reader. close ();} return sb. toString ();}}

I think this is a fixed class. I can use it as long as JSON is used. I haven't tried it yet. I don't know if it's right.

package com.example.mychat;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import org.json.JSONArray;import org.json.JSONObject;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.ListView;import android.widget.SimpleAdapter;import com.four.http.httpcontent;public class User_tips extends Activity {httpcontent content = new httpcontent();private Button btnshua;private ListView xianshi;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_user_tips);btnshua = (Button) findViewById(R.id.btnshua);xianshi = (ListView) findViewById(R.id.listView1);btnshua.setOnClickListener(new shualistener());}class shualistener implements OnClickListener {@Overridepublic void onClick(View v) {// TODO Auto-generated method stublistxianshi();}}private List
  
   > getmessg(String url) {List
   
    > list = new ArrayList
    
     >();String body;try {body = content.getContent(url);JSONArray array = new JSONArray(body);for (int i = 0; i < array.length(); i++) {JSONObject obj = array.getJSONObject(i);Map
     
       map = new HashMap
      
       ();map.put("foundname", obj.getString("foundname"));map.put("foundplace", obj.getString("foundplace"));list.add(map);}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}return list;}private void listxianshi(){try {String url = "http://10.20.180.34:8080/lostfound/JSONDemoServlet";SimpleAdapter adapter = new SimpleAdapter(this,getmessg(url), R.layout.list_item, new String[] {"foundname", "username" }, new int[] {R.id.foundname, R.id.username });xianshi.setAdapter(adapter);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
      
     
    
   
  

:


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.