日期:2014-05-16  浏览次数:20356 次

android取得json数据
步骤一:页面返回JSON数据。

对本空间日志“php和AJAX的简单实现”的json.php代码做一些简单修改,代码如下:将代码 echo $_GET['jsoncallback'].'('.custom_json::encode($big_test).')';

改为 echo $_GET['jsoncallback'].custom_json::encode($big_test);

将文件另存为jsondata.php。

步骤二:编写Android代码。

1.编写Contact类,设置set和get方法。

package com.domain;

public class Contact {
private String name;
private int age;
private int sex;
private Double height;
private boolean is_human;
private String string;

public Contact() { }

public Contact(String name, int age, int sex, Double height,
   boolean is_human, String string) {
  this.name = name;
  this.age = age;
  this.sex = sex;
  this.height = height;
  this.is_human = is_human;
  this.string = string;
}
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public int getSex() {
return sex;
}

public void setSex(int sex) {
this.sex = sex;
}

public Double getHeight() {
return height;
}

public void setHeight(Double height) {
this.height = height;
}

public boolean isIs_human() {
return is_human;
}

public void setIs_human(boolean is_human) {
this.is_human = is_human;
}

public String getString() {
return string;
}

public void setString(String string) {
this.string = string;
}

}

2.编写输入流处理工具类StreamTools。

package com.shao.utils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

public class StreamTools {
public static byte[] readInputStream(InputStream instream) throws Exception{
  ByteArrayOutputStream outstream = new ByteArrayOutputStream();
  byte[] buf = new byte[1024];
  int len = 0 ;
  while(( len = instream.read(buf)) != -1)
  {
   outstream.write(buf, 0, len);
  }
  byte[] data = outstream.toByteArray();//网页的二进制数据
  outstream.close();
  instream.close();
  return data;
 
}

}

3.编写android布局文件main.xml。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView
android:id="@+id/name"
  android:layout_width="100dip"
    android:layout_height="wrap_content"
/>

<ListView
android:id="@+id/listview"
  android:layout_width="fill_parent"
    android:layout_height="wrap_content"
/>
</LinearLayout>

新建布局文件item.xml。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView
android:id="@+id/name"
  android:layout_width="100dip"
    android:layout_height="wrap_content"
/>
  <TextView
android:id="@+id/sex"
  android:layout_width="100dip"
    android:layout_height="wrap_content"
/>