Android 解析JSONObject以及JSONArray对比

在Android客户端与服务器交互的过程中,客户端一般采用json解析服务器的返回数据。此时有两种数据格式。但其根本都是字符串或字符串数组!

1、JSONObject

下面是PHP端代码:

<?php
$array = array(
  ‘username‘=>‘lhh‘,
  ‘password‘=>‘123456‘,
  ‘user_id‘=>‘1‘
);
echo json_encode($array);
?>

我们这里只是模拟,所以,在没有服务器的情况下,也可以在java代码中定义,如下:

String strJson = "{"username":"lhh","password":"123456","user_id":"1"}";

下面是android代码:

//by 不剃头的一休哥 2014//11/15

package com.example.jsonjs;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		new Thread(new Runnable(){

			@Override
			public void run() {
				Looper.prepare();
				// TODO Auto-generated method stub
				HttpClient client = new DefaultHttpClient();
			    StringBuilder builder = new StringBuilder();
			    //地址根据实际情况而定
			    HttpGet myget = new HttpGet("http://192.168.1.104/login.php");
			    try {
			        HttpResponse response = client.execute(myget);
			        BufferedReader reader = new BufferedReader(new InputStreamReader(
			        response.getEntity().getContent()));
			        for (String s = reader.readLine(); s != null; s = reader.readLine()) {
			            builder.append(s);
			        }
			        //转化为JSONObject
			        JSONObject jsonObject = new JSONObject(builder.toString());
			        String re_username = jsonObject.getString("username");
			        String re_password = jsonObject.getString("password");
			        
			        //setTitle("用户id_"+re_user_id);
			        Log.v("url response", "true="+re_username);
			        Log.v("url response", "true="+re_password);
			        //tv1.setText(re_username);
			        //tv2.setText(re_password);
			        //Toast.makeText(getApplicationContext(), re_username, Toast.LENGTH_LONG).show();
			    } catch (Exception e) {
			        Log.v("url response", "false");
			       // Toast.makeText(getApplicationContext(), "false", Toast.LENGTH_LONG).show();
			        e.printStackTrace();
			    }
			    Looper.loop();
			}}).start();				
	}
}

该代码需要服务器,如果是在java定义的json数据。

2、JSONArray

下面是PHP代码(我用到了数据库)

<?php
$link=mysql_connect("localhost","username","password");
mysql_query("SET NAMES utf8");
mysql_select_db("test",$link);
$sql=mysql_query("select * from teacher ",$link);
while($row=mysql_fetch_assoc($sql))
    $output[]=$row;
echo json_encode($output);
mysql_close();
?>

当然也可以仿照上述在java代码中定义,如下:

String strJson = "[{"id":"1","name":"wang"},{"id":"2","name":"liu"}]";

下面是android代码:

//by 不剃头的一休哥 2014/11/15

package com.example.jsonjsarr;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);		
		new Thread(new Runnable() {			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Looper.prepare();
				getServerJsonDataWithTypes();
				Looper.loop();
			}
		}).start();
		
		
	}
	private void getServerJsonDataWithTypes() {
		// TODO Auto-generated method stub
		
		int res = 0;
		HttpClient client = new DefaultHttpClient();
		StringBuilder str = new StringBuilder();
		//此处地址根据实际情况而定
		HttpGet httpGet = new HttpGet("http://192.168.1.104/login.php");
		
		try{	
			
			HttpResponse httpRes = client.execute(httpGet);			
			res = httpRes.getStatusLine().getStatusCode();			
			if(res == 200)
			{
				BufferedReader buffer = new BufferedReader(new InputStreamReader(httpRes.getEntity().getContent()));
				String s = buffer.readLine();				
				for(;s!=null;s=buffer.readLine())
				{
					str.append(s);					
				}
				//字符串转化为JSONArray			
				JSONArray json = new JSONArray(str.toString());			
				String strs=" ";				
				for(int i = 0;i<json.length();i++)
				{
					//按照下标进行访问
					JSONObject jsonobject = (JSONObject)json.opt(i);
					strs += jsonobject.getString("name");
				}				
				
				Toast.makeText(getApplicationContext(), strs, Toast.LENGTH_LONG).show();
			}
			else{
				Toast.makeText(getApplicationContext(), "httperror", Toast.LENGTH_LONG).show();
			}
		}catch(Exception e){
			
			Log.v("test", "exception");
		}
	}

	
}

  

综上两种可以看出,其本质都是一样,一个JSONArray分成多个JSONObject进行操作。

顺便说下:

1、在Android 4.X中,进行网络访问时不要放在主线程里,否则APP可能会强制退出。

2、注意UI线程与非UI线程的区别。

3、Looper.prepare()与Looper.loop()的作用。

4、需要网络访问时,别忘了在mainfest里添加权限

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

5、小弟不才,如有错误,还请指出。

6、代码虽然是我写的,但是有问题尽量不要找我,是他自己长歪了。  

7、转载请注明出处。

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。