在Android开发过程中,或更新数据,或为减轻手机负担将大部分复杂运算交由服务器来进行,都需要与服务器之间进行数据交互,数据交互中,使用的较为频繁的格式变为json数据,书写便捷,操作方便,本文就对于客户端对于获取的json数据的解析进行一定的介绍。了解不是很深刻,只敢说简单应用,请测能用。
json数据书写比较简单,如下:
{
"age": "24",
"gender": "男",
"hobby": "跑步,看书等",
"name": "hill"
}
注意保存json文件时,格式要进行确定一直,特别是对于里面还有中文的时候。不然可能会出现乱码情况。
而后就可以放置在服务器进行发布了。
界面布局比较随意,只是为了演示:
界面代码为一个下载button,一个LinearLayout用于添加textview显示信息;
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="下载"
android:onClick="loadjson"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/ll_show"
android:orientation="vertical">
</LinearLayout>
下载并解析json文件如下:
public void loadjson(View view) {
new Thread(){
@Override
public void run() {
try {
URL Url=new URL("http://192.168.43.55:8080/jsonx.json");
HttpURLConnection conn=(HttpURLConnection)Url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5000);
int code = conn.getResponseCode();
if (code==200){
InputStream inputStream = conn.getInputStream();
String s = ToString(inputStream);
jiexi(s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
private void jiexi(String s) throws JSONException {//解析显示数据
JSONObject object=new JSONObject(s);
System.out.println(s);
String name = object.getString("name");
String gender = object.getString("gender");
String age = object.getString("age");
String hobby = object.getString("hobby");
final String[] strings = {name, gender, age, hobby};
runOnUiThread(new Runnable() {
@Override
public void run() {
for (String s :
strings) {
TextView textView=new TextView(getApplicationContext());
textView.setTextColor(Color.BLACK);
textView.setText(s);
ll_show.addView(textView);
}
}
});
}
private String ToString(InputStream in) throws IOException {//将下载下来的流转换为string
ByteArrayOutputStream baos=new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len=-1;
while ((len=in.read(bytes))!=-1){
baos.write(bytes,0,len);
}
in.close();
String s=new String(baos.toByteArray());
return s;
}
结果如下:
案例中用到了,利用java代码为线性布局添加控件:
TextView textView=new TextView(getApplicationContext());
textView.setTextColor(Color.BLACK);
textView.setText(s);
ll_show.addView(textView);
还是比较简单的,无需赘述。