日期:2014-05-19  浏览次数:20834 次

求在servlet操作Mysql得到json对象的方法
首先配置的时候好像需要在jdk7\lib里面还有tomcat的lib目录加入mysql-connector-java-5.1.18-bin.jar和mm.mysql,可是我 在网上怎么也找不到mm.mysql这个文件…
  另外求有没有简单范例,或文档或哪本书的哪个部分专门讲这个

------解决方案--------------------
可以直接从mysql中读出json格式的?有这么方便的吗?应该组装一下吧。
看下这个,看有用没
http://wenku.it168.com/d_000265852.shtml
------解决方案--------------------
<?php
if(isset($_GET['user']) && intval($_GET['user'])) {
 
 
$format = strtolower($_GET['format']) == 'json' ? 'json' : 'xml'; //xml is the default
$user_id = intval($_GET['user']); //no default
 
/* 连接数据库*/
$link = mysql_connect('localhost','root','xxxxx') or die('Cannot connect to the DB');
mysql_select_db('jsonAndroid',$link) or die('Cannot select the DB');
 
$query = "SELECT * FROM `users`;";
$result = mysql_query($query,$link) or die('Errant query: '.$query);
 
$posts = array();
if(mysql_num_rows($result)) {
while($post = mysql_fetch_assoc($result)) {
$posts[] = array('post'=>$post);
}
}
 
/* json格式*/
if($format == 'json') {
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));
}
else {
header('Content-type: text/xml');
echo '<posts>';
foreach($posts as $index => $post) {
if(is_array($post)) {
foreach($post as $key => $value) {
echo '<',$key,'>';
if(is_array($value)) {
foreach($value as $tag => $val) {
echo '<',$tag,'>',htmlentities($val),'</',$tag,'>';
}
}
echo '</',$key,'>';
}
}
}
echo '</posts>';
}
 
}
 ?>
则可以把数据表输出为JSON或者XML格式了.客户端的Android调用: 

try {

HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);

HttpParams p = new BasicHttpParams();

p.setParameter("user", "1");
 

HttpClient httpclient = new DefaultHttpClient(p);
String url = "http://10.0.2.2:8082/myphp/phpWebservice/webservice1.php?user=1&format=json";
HttpPost httppost = new HttpPost(url);
 

try {
Log.i(getClass().getSimpleName(), "send task - start");

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair("user", "1"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost,
responseHandler);
// 解析JSON返回的 JSONObject json = new JSONObject(responseBody);
JSONArray jArray = json.getJSONArray("posts");
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
 
for (int i =