android獲取json
㈠ android怎麼得到php發來的json數據
使用守則
首先,我們要創建Web服務,從Mysql資料庫中讀取數據。
<?php
<pre>/* require the user as the parameter */
<pre>//http://localhost:8080/sample1/webservice1.php?user=1
if(isset($_GET['user']) && intval($_GET['user'])) {
/* soak in the passed variable or set our own */
$number_of_posts = isset($_GET['num']) ? intval($_GET['num']) : 10; //10 is the default
$format = strtolower($_GET['format']) == 'json' ? 'json' : 'xml'; //xml is the default
$user_id = intval($_GET['user']); //no default
/* connect to the db */
$link = mysql_connect('localhost','root','123456') or die('Cannot connect to the DB');
mysql_select_db('TEST',$link) or die('Cannot select the DB');
/* grab the posts from the db */
//$query = "SELECT post_title, guid FROM wp_posts WHERE post_author =
// $user_id AND post_status = 'publish' ORDER BY ID DESC LIMIT $number_of_posts";
$query = "SELECT * FROM `test`.`users`;";
$result = mysql_query($query,$link) or die('Errant query: '.$query);
/* create one master array of the records */
$posts = array();
if(mysql_num_rows($result)) {
while($post = mysql_fetch_assoc($result)) {
$posts[] = array('post'=>$post);
}
}
/* output in necessary format */
if($format == 'json') {
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));
}
else {
header('Content-type: text/xml');
echo '';
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 '';
}
/* disconnect from the db */
@mysql_close($link);
}
?>
下面是代碼為Android活動讀取Web服務和解析JSON對象:
public void clickbutton(View v) {
try {
// http://androidarabia.net/quran4android/phpserver/connecttoserver.php
// Log.i(getClass().getSimpleName(), "send task - start");
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
//
HttpParams p = new BasicHttpParams();
// p.setParameter("name", pvo.getName());
p.setParameter("user", "1");
// Instantiate an HttpClient
HttpClient httpclient = new DefaultHttpClient(p);
String url = "http://10.0.2.2:8080/sample1/" +
"webservice1.php?user=1&format=json";
HttpPost httppost = new HttpPost(url);
// Instantiate a GET HTTP method
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);
// Parse
JSONObject json = new JSONObject(responseBody);
JSONArray jArray = json.getJSONArray("posts");
ArrayList<HashMap<String, String>> mylist =
new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = jArray.getJSONObject(i);
String s = e.getString("post");
JSONObject jObject = new JSONObject(s);
map.put("isers", jObject.getString("isers"));
map.put("UserName", jObject.getString("UserName"));
map.put("FullName", jObject.getString("FullName"));
mylist.add(map);
}
Toast.makeText(this, responseBody, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Log.i(getClass().getSimpleName(), "send task - end");
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
}
這里是PHP代碼,將數據發送到Web服務,並將其保存:
<?php
//$json=$_GET ['json'];
$json = file_get_contents('php://input');
$obj = json_decode($json);
//echo $json;
//Save
$con = mysql_connect('localhost','root','123456')
or die('Cannot connect to the DB');
mysql_select_db('TEST',$con);
/* grab the posts from the db */
//$query = "SELECT post_title, guid FROM wp_posts WHERE
// post_author = $user_id AND post_status = 'publish'
// ORDER BY ID DESC LIMIT $number_of_posts";
mysql_query("INSERT INTO `test`.`users` (UserName, FullName)
VALUES ('".$obj->{'UserName'}."', '".$obj->{'FullName'}."')");
mysql_close($con);
//
//$posts = array($json);
$posts = array(1);
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));
?>
Android的活動,將數據發送到Web服務作為一個JSON對象保存在MySQL資料庫中
public void clickbuttonRecieve(View v) {
try {
JSONObject json = new JSONObject();
json.put("UserName", "test2");
json.put("FullName", "1234567"); HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);
//
//String url = "http://10.0.2.2:8080/sample1/webservice2.php?" +
// "json={\"UserName\":1,\"FullName\":2}";
String url = "http://10.0.2.2:8080/sample1/webservice2.php";
HttpPost request = new HttpPost(url);
request.setEntity(new ByteArrayEntity(json.toString().getBytes(
"UTF8")));
request.setHeader("json", json.toString());
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
if (entity != null) {
InputStream instream = entity.getContent();
String result = RestClient.convertStreamToString(instream);
Log.i("Read from server", result);
Toast.makeText(this, result,
Toast.LENGTH_LONG).show();
}
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
}
知識點
要連接到你的模擬器,你可以使用此鏈接:http://10.0.2.2:8080/。
要讀取JSON對象在Web服務中,您可以使用下面這行代碼:
$json = file_get_contents('php://input');
$obj = json_decode($json);
㈡ android如何從網頁中獲取一個json數組並解析出來,顯示在textview裡面
1,先要建立一個線程獲取json數據
2接著解析json數據
3,設置textview
例如:json數據,strjson= {"key": ["a","b"]}
JSONObject object = new JSONObject (strjson)
JSONArray arr= object.getJSONArray("key") ;
String text=arr.getString(0);
㈢ Android 中解析 JSON
JSON( javaScript Object Notation ) 是一種輕量級的數據交換格式。易於閱讀和編寫,同時也易於機器解析和生成。
JSON 建構於兩種結構:
JSON 具有以下這些格式:
參考: Android 中 解析 JSON
Android 提供類四種不同的類來操作 JSON 數據。這些類是 JSONArray、JSONObject、JSONStringer 和 JSONTokenizer
為了解析 JSON 對象,須先創建一個 JSONObject 類的對象,需要傳入需解析的字元串 JSONObject root = new JSONObject(candyJson); 然後根據 JSONObject 對象提供方法以及數據類型解析對應 json 數據。下表展示一些 JSONObiect 提供的方法
示例:
㈣ android 用JSON 解析數據介面方法
介面獲取下來的數據為
{"status":200,"message":"查詢成功","data":{"id":32,"user_id":null,"user_code":null,"user_pass":null,"meeting_id":"1","meeting_pass":null,"config_param_ip":"11.1.1.70","port":"6501","web_config_param_ip":"11.1.1.70","web_port":"6501","unit_code":null,"create_time":null,"update_time":null,"status":0,"userCode":"video1","userPass":"video1","meetingId":"1","meetingPass":"","apiPort":"13000","username":"admin","password":"123456","updateTime":"2021-11-08 17:45:29"}}
使用方法
try {
JSONObject jsonObject = new JSONObject(outstring);
int resultCode = jsonObject.getInt("status");
if (resultCode == 200) {
JSONObject obj = jsonObject.getJSONObject("data");
IP = obj.getString("config_param_ip");
port = obj.getString("web_port");
username = obj.getString("userCode");
password = obj.getString("userPass");
roomID = Integer.parseInt(obj.getString("meetingId"));
roomPassword = obj.getString("password");
} else {
ToastUtils.showShort("查詢失敗");
}
goVideo();
} catch (Exception e) {
e.printStackTrace();
}
㈤ Android 獲取不到json數據
1,先要建立一個線程獲取json數據
2接著解析json數據
3,設置textview
例如:json數據,strjson=
{"key":
["a","b"]}
jsonobject
object
=
new
jsonobject
(strjson)
jsonarray
arr=
object.getjsonarray("key")
;
string
text=arr.getstring(0);
㈥ android怎麼讀取外部json文件
比如說讀取sd卡里的
privatestaticStringSDCardPATH=Environment.getExternalStorageDirectory()+"/";
/**
*讀取文本文件
*
*@paramfilePath
*@return
*/
(StringfilePath){
StringBuildersb=newStringBuilder();
try{
Filefile=newFile(SDCardPATH+filePath);
InputStreamin=null;
in=newFileInputStream(file);
inttempbyte;
while((tempbyte=in.read())!=-1){
sb.append((char)tempbyte);
}
in.close();
}catch(Exceptione){
e.printStackTrace();
}
returnsb.toString();
}
然後你就可以進行你的解析json了。
㈦ Android讀取本地json文件的方法
本文實例講述了Android讀取本地json文件的方法。分享給大家供大家參考,具體如下:
1、讀取本地JSON ,但是顯示漢字亂碼
public static String readLocalJson(Context context, String fileName){ String jsonString=""; String resultString=""; try { BufferedReader bufferedReader=new BufferedReader(new InputStreamReader( context.getResources().getAssets().open(fileName))); while ((jsonString=bufferedReader.readLine())!=null) { resultString+=jsonString; } } catch (Exception e) { // TODO: handle exception } return resultString;}
2、讀取本地JSON,顯示漢字正確,txt文件設置時UTF-8,UNIX
public static String readLocalJson(Context context, String fileName){ String jsonString=""; String resultString=""; try { InputStream inputStream=context.getResources().getAssets().open(fileName); byte[] buffer=new byte[inputStream.available()]; inputStream.read(buffer); resultString=new String(buffer,"GB2312"); } catch (Exception e) { // TODO: handle exception } return resultString;}
㈧ android怎麼樣獲取並解析json數據
json數據 是從介面獲取來的 其實就是一串字元串 可以用Gson解析。
Gson gson =new Gson( ),然後調用fromJson 方法解析
㈨ android 解析json用那個包裡面的方法比較好呢
android 解析json還有用Google出品的Gson比較好,具體步驟為:
1、首先,從 code.google.com/p/google-gson/downloads/list下載GsonAPI:
google-gson-1.7.1-release.zip 把gson-1.7.jar 到libs(項目根目錄新建一個libs文件夾)中。 可以使用以下兩種方法解析JSON數據,通過獲取JsonReader對象解析JSON數據。
代碼如下:
String jsonData = "[{\"username\":\"arthinking\",\"userId\":001},{\"username\":\"Jason\",\"userId\":002}]";
try{
JsonReader reader = new JsonReader(new StringReader(jsonData));
reader.beginArray();
while(reader.hasNext()){
reader.beginObject();
while(reader.hasNext()){
String tagName = reader.nextName();
if(tagName.equals("username")){
System.out.println(reader.nextString());
}
else if(tagName.equals("userId")){
System.out.println(reader.nextString());
}
}
reader.endObject();
}
reader.endArray();
}
catch(Exception e){
e.printStackTrace();
}
2、使用Gson對象獲取User對象數據進行相應的操作:
代碼如下:
Type listType = new TypeToken<LinkedList<User>>(){}.getType();
Gson gson = new Gson();
LinkedList<User> users = gson.fromJson(jsonData, listType);
for (Iterator iterator = users.iterator(); iterator.hasNext();) {
User user = (User) iterator.next();
System.out.println(user.getUsername());
System.out.println(user.getUserId());
}
3、如果要處理的JSON字元串只包含一個JSON對象,則可以直接使用fromJson獲取一個User對象:
代碼如下:
String jsonData = "{\"username\":\"arthinking\",\"userId\":001}";
Gson gson = new Gson();
User user = gson.fromJson(jsonData, User.class);
System.out.println(user.getUsername());
System.out.println(user.getUserId());