欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android4.0 对网络Jason对象的解析(二) 客户端

程序员文章站 2022-05-30 14:38:04
...

      1.要在客户端实现对Json对象的解析,首先我们在清单文件加好权限:可以上网的权限,注意,在此之时,也一定要看看设备有没有联网,就是说,要上网权限,手机也要同时联网。

         

 <uses-permission android:name="android.permission.INTERNET"/>

       2.建立一个工具类去实现并处理一些东西,如:Http去获取InputStream,将InputStream转换成对应的JsonString,然后在将其封装成一个javaBean类传给Activitiy前台显示

package com.example.json_demo;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

import com.example.domain.Person;

public class HttpUtils {

	public HttpUtils() {
		// TODO Auto-generated constructor stub
	}

	public static String GetJsonString(String urlstr) {
        //通过Http协议去得到对应InputStream
		String Jsonstring = "";
		try {
			URL url = new URL(urlstr);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(3000);
			conn.setRequestMethod("GET");
			conn.setDoInput(true);
			InputStream input = conn.getInputStream();
			int code = conn.getResponseCode();
			System.out.println("-->>response code" + code);
			//如果说这个连接成功,就将input变成一个JsonString,
			//一般来说对应的JsonString是 {‘Key’:‘Value’}
			if (code == 200) {
				Jsonstring = changeInputStreamToString(input);
				System.out.println("--》JsonString" + Jsonstring);
				
			}

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return Jsonstring;
	}

	private static String changeInputStreamToString(InputStream input) {
		// 通过 byteArrayoutputStream 写入byte然后转换成string类型
		String jsonstr = "";
		ByteArrayOutputStream byteout = new ByteArrayOutputStream();
		byte[] by = new byte[4 * 1024];
		int len = 0;
		try {
			while (len != -1) {
				byteout.write(by, 0, len);
				len = input.read(by);
			}
			jsonstr = new String(byteout.toByteArray());

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return jsonstr;
	}

	// 通过JsonStrng得到对应Json 的对象
	public static Person getPersonObject(String key, String JsonStr) {

		Person person = new Person();
		try {
			// 将怎么个大的String变成一个 JSON 对象
			JSONObject jsonObject = new JSONObject(JsonStr);
			// 取其中的key后面的变成value 后的 Json对象
			JSONObject personPobject = jsonObject.getJSONObject(key);
			//将 Json中的对象的值,转换成JavaBean的对象的属性值
			person.setId(personPobject.getInt("id"));
			person.setAge(personPobject.getInt("age"));
			person.setName(personPobject.getString("name"));

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return person;
	}
}
Person 类:
package com.example.domain;
public class Person {
	private int id;
	private String name;
	private String address;
	private int age;

	public Person(int id, String name, String address, int age) {
		super();
		this.id = id;
		this.name = name;
		this.address = address;
		this.age = age;
	}

	public Person() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", address=" + address
				+ ", age=" + age + "]";
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

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

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
}
主要的Activity
package com.example.json_demo;

import com.example.domain.Person;

import android.location.GpsStatus.Listener;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends ActionBarActivity {
	private Runnable run;

	private Button button1, button2, button3, button4;

	private String str = "";

	private OnClickListener listener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// 新的线程去实现对应的方法
			
			switch (v.getId()) {
			case R.id.Button:
				run = new Runnable() {
					// 通过子线程去获取到Jsson
					public void run() {
						String path = "http://192.168.1.4:8080/BackWen/servlet/JsonAction?action_flag=person";
						str = HttpUtils.GetJsonString(path);
						Person person = HttpUtils.getPersonObject("person", str);
						System.out.println("--> Person" + person.getAge());
					}
				};
				Thread mythread = new Thread(run);
				mythread.start();
				System.out.println(str);
				break;
			case R.id.Button1:

				break;
			case R.id.Button2:

				break;
			case R.id.Button3:

				break;
			}

		}
	};

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		//初始化各个组件
		button1 = (Button) findViewById(R.id.Button);
		button2 = (Button) findViewById(R.id.Button1);
		button3 = (Button) findViewById(R.id.Button2);
		button4 = (Button) findViewById(R.id.Button3);
        //添加监听
		button1.setOnClickListener(listener);
		button2.setOnClickListener(listener);
		button3.setOnClickListener(listener);
		button4.setOnClickListener(listener);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}
 最后就是对应得布局,很简单
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.json_demo.MainActivity" >

    <Button
        android:id="@+id/Button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="解析Json object" />