def index() { def parg=params if(params.data){ //如果存在data参数,将该参数转换为JSONObject JSONObject json=new JSONObject(params.data) def sqlinsert=new Sql(dataSource) //从JSONObject中获取数据并插入数据库 sqlinsert.executeInsert(" INSERT INTO person (name,gender,title) values (?,?,?)", [json.getString("name"),json.getString("gender"),json.getString("title")]) } def sql= new Sql(dataSource) //获取Person列表,以JSON方式返回 def rows=sql.rows("select name,gender,title from person") sql.close() render rows as JSON }
public void doHttpGetJSON(View view) throws IOException, JSONException { DefaultHttpClient httpClient = new DefaultHttpClient(); //指定服务器端URL HttpGet get = new HttpGet("http://10.4.30.228:8080/PersonForAndroid/person"); HttpResponse rsp = httpClient.execute(get); //获取响应的实体 HttpEntity httpEntity = rsp.getEntity(); //将响应的实体转换为字符串 String jsonString = EntityUtils.toString(httpEntity); //服务器端返回的数据格式为:[{"name":"Johnny","gender":"Male","title":"Programmer"},{"name":"Kevin","gender":"Male","title":"Manager"}] //是一个JSON数组,因此使用JSONArray将字符串转换为JSONArray //如果服务器端返回的是JSON字符串:{"name":"Johnny","gender":"Male","title":"Programmer"},则使用JSONObject jsonObject=new JSONObject(jsonString); JSONArray jsonArray=new JSONArray(jsonString); String resultsString=""; //遍历JSONArray,将结果输出 for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObj = jsonArray.getJSONObject(i); String name = jsonObj.getString("name"); String gender = jsonObj.getString("gender"); String title = jsonObj.getString("title"); resultsString += title + " " + name + " is " + gender+"\r\n"; } TextView getTextView = (TextView) findViewById(R.id.jsonGetTextView); getTextView.setText(resultsString); }
public void doHttpPostJSON(View view) throws IOException, JSONException { //定义一个JSON,用于向服务器提交数据 JSONObject jsonObj = new JSONObject(); jsonObj.put("name", getTextFromView(R.id.name)) .put("gender", getTextFromView(R.id.gender)) .put("title", getTextFromView(R.id.title)); String jsonString = jsonObj.toString(); //指定Post参数 List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("data", jsonString)); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost post = new HttpPost("http://10.4.30.228:8080/PersonForAndroid/person"); post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse rsp = httpClient.execute(post); HttpEntity httpEntity = rsp.getEntity(); String displayString = EntityUtils.toString(httpEntity); TextView getTextView = (TextView) findViewById(R.id.jsonPostTextView); getTextView.setText(displayString); }