将List转化为Json并上传

下面的例子实现了:查询数据,并封装为json串,然后上传,并取得返回数据。

<1>从数据库查询多张表的数据,分别放入List中,封装成TableData

<2>把多个TableData放入List中,然后将最后的list转化成json串

<3>采用POST方式上传:把json串放入NameValuePair,然后设置到httpPost中

<4>上传并返回httpResponse

<5>取得返回的字符串,成功返回true,失败返回false

	private static String IP = "http://" + VISConstant.IP;
	// 实现功能:从数据库查询多张表数据,并封装成json串,然后上传
	public Boolean uploadResult(Context context) {	
		Boolean flag = false;
		DataService dataService = new DataService(context);
		
		//查询(登录日志表)并放入TableData
		List loginList = new ArrayList();
		loginList = dataService.queryAllLoginRecord();
		TableData tableData1 = new TableData();
		tableData1.setTableName(VISConstant.TABLE_LOGINRECORDINFO);
		tableData1.setTableData(loginList);

		//查询(查验结果表)并放入TableData
		List checkList = new ArrayList();
		checkList = dataService.queryAllCheckRecordInfo();
		TableData tableData2 = new TableData();
		tableData2.setTableName(VISConstant.TABLE_CHECKRECORDINFO);
		tableData2.setTableData(checkList);

		//查询(查验结果明细表)并放入TableData
		List detailList = new ArrayList();
		detailList = dataService.queryAllCheckRecordDetails();
		TableData tableData3 = new TableData();
		tableData3.setTableName(VISConstant.TABLE_CHECKRECORDDETAIL);
		tableData3.setTableData(detailList);
		
		//将TableData放入List中
		List retList = new ArrayList();
		retList.add(tableData1);
		retList.add(tableData2);
		retList.add(tableData3);
		 
		//将List转换成json串
		Gson gson = new Gson();
		String s = gson.toJson(retList);
		System.out.println(s);
		
		List params = new ArrayList();
		params.add(new BasicNameValuePair("jsonStr",s));
//		String url = "http://192.168.173.1:8888/VIS/UploadResultServlet";
		String url = IP + ":8888/VIS1.3/UploadResultServlet";
        	HttpPost httpPost = new HttpPost(url);      
		try {
			//把NameValuePair设置到httpPost中
			httpPost.setEntity(new UrlEncodedFormEntity(params,"utf-8"));
			HttpClient httpClient = new DefaultHttpClient();
			HttpResponse httpResponse;
			//返回httpResponse
			httpResponse = httpClient.execute(httpPost);
			String isSuccess = "";
			//请求成功
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				// 取得返回的字符串
				isSuccess = EntityUtils.toString(httpResponse.getEntity());
				if ("true".equals(isSuccess)) {
					flag = true;
				} else {
					flag =false;
				}
			}
			System.out.println(isSuccess);
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
		}	
		return flag;
	}

你可能感兴趣的:(将List转化为Json并上传)