JsonObject生成Json字符串,并且解析为对象-----JsonReader解析Json字符串

MainActivity

package com.example.gsondemo;

import java.io.IOException;

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

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity {
	private String jsonDate = "["
	           + "{\"id\": 912345678901,"
	           + "\"text\":\"How do I read JSON onAndroid?\","
	            + "\"geo\":null,"
	           +"\"user\":{\"name\":\"android_newb\",\"followers_count\":41}},"
	           + "{\"id\": 912345678902,"
	           + "\"text\":\"@android_newb just useandroid.util.JsonReader!\","
	           + "\"geo\":[50.454722,-104.606667],"
	           +"\"user\":{\"name\":\"jesse\",\"followers_count\":2}}"
	           + "]";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		try {
			/**
			 * 1、JsonReader解析json字符串,根据需求生成对象
			 */
			new JsonUtils().parseJson(jsonDate);
		} catch (IOException e1) {
			// Todo Auto-generated catch block
			e1.printstacktrace();
		}
		try {
			/**
			 * 2、JsonObject生成json字符串
			 */
			String createJson = createJson();
			Log.i("TAG","createJson:::" + createJson);
			/**
			 * 3、JsonObject解析json字符串
			 */
			pareJson(createJson);
		} catch (JSONException e) {
			// Todo Auto-generated catch block
			e.printstacktrace();
		}

	}

	
	
	/**
	 * 1、生成Json字符串
	 * {"intKey":123,"doubleKey":10.1,"longKey":666666666,"stringKey":"lalala",* "booleanKey"
	 * :true,"arrayKey":[111,"second"],"innerObjectKey":{"innerStr":"inner"}}
	 */
	private String createJson() throws JSONException {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("intKey",123);
		jsonObject.put("doubleKey",10.1);
		jsonObject.put("longKey",666666666);
		jsonObject.put("stringKey","lalala");
		jsonObject.put("booleanKey",true);

		JSONArray jsonArray = new JSONArray();
		jsonArray.put(111);
		jsonArray.put("second");
		jsonObject.put("arrayKey",jsonArray);

		JSONObject innerjsonObject = new JSONObject();
		innerjsonObject.put("innerStr","inner");
		jsonObject.put("innerObjectKey",innerjsonObject);


		return jsonObject.toString();
	}

	private void pareJson(String jsonStr) throws JSONException {
		JSONObject jsonObject = new JSONObject(jsonStr);
		int intValue = jsonObject.optInt("intKey");
		double doubleValue = jsonObject.optDouble("doubleKey");
		long longValue = jsonObject.optLong("longKey");
		String strValue = jsonObject.optString("stringKey");
		boolean boolValue = jsonObject.optBoolean("booleanKey");

		JSONArray array = jsonObject.optJSONArray("arrayKey");
		int arrIntValue = array.optInt(0);
		String arrStrValue = array.optString(1);

		JSONObject innerjson = jsonObject.optJSONObject("innerObjectKey");
		String innerStr = innerjson.optString("innerStr");

		Log.e("Json","intValue = " + intValue + ",doubleValue = "
				+ doubleValue + ",longValue = " + longValue
				+ ",strValue = " + strValue + ",booleanValue = "
				+ boolValue + ",arrIntValue = " + arrIntValue
				+ ",arrStrValue = " + arrStrValue + ",innerStr = "
				+ innerStr);
	}
}

JsonUtils
package com.example.gsondemo;

import java.io.IOException;
import java.io.StringReader;
import android.util.JsonReader;
import android.util.JsonToken;
import android.util.Log;

public class JsonUtils {
	/**
	 * [
   {
    "id": 912345678901,"text": "How do I read JSON on Android?","geo": null,"user": {
       "name": "android_newb","followers_count": 41
    } 
   },{
    "id": 912345678902,"text": "@android_newb just useandroid.util.JsonReader!","geo": [50.454722,"user": {
      "name": "jesse","followers_count": 2
    }
   }
 ]
	 */
	public void parseJson(String jsonDate) throws IOException {
		// 创建JsonReader对象
		JsonReader jsReader = new JsonReader(new StringReader(jsonDate));
		jsReader.beginArray();
		while (jsReader.hasNext()) {
			readMessage(jsReader);
		}
		jsReader.endarray();

	}

	public void readMessage(JsonReader jsReader) throws IOException {
		jsReader.beginobject();
		while (jsReader.hasNext()) {
			String tagName = jsReader.nextName();
			if (tagName.equals("id")) {
				Log.i("TAG","name:" + jsReader.nextLong());
			} else if (tagName.equals("text")) {
				Log.i("TAG","text:" + jsReader.nextString());
			} else if (tagName.equals("geo")
					&& jsReader.peek() != JsonToken.NULL) {
				readDoubleArray(jsReader);
			} else if (tagName.equals("user")) {
				readUser(jsReader);
			} else {
				// 跳过当前值
				jsReader.skipValue();
				Log.i("TAG","skip======>");
			}
		}
		jsReader.endobject();
	}

	// 解析geo中的数据
	public void readDoubleArray(JsonReader jsReader) throws IOException {
		jsReader.beginArray();
		while (jsReader.hasNext()) {
			Log.i("TAG","readDoubleArray:" + jsReader.nextDouble());
		}
		jsReader.endarray();
	}

	/**
	 * 
	 * "user": { "name": "jesse","followers_count": 2 } 由于读取user中的数据
	 * 
	 * @param jsReader
	 * @throws IOException
	 */
	public void readUser(JsonReader jsReader) throws IOException {
		String userName = null;
		int followsCount = -1;

		jsReader.beginobject();
		while (jsReader.hasNext()) {
			String tagName = jsReader.nextName();
			if (tagName.equals("name")) {
				userName = jsReader.nextString();
				Log.i("TAG","user_name:" + userName);
			} else if (tagName.equals("followers_count")) {
				followsCount = jsReader.nextInt();
				Log.i("TAG","followers_count:" + followsCount);
			}
		}
		jsReader.endobject();
	}
}

相关文章

AJAX是一种基于JavaScript和XML的技术,能够使网页实现异步交...
在网页开发中,我们常常需要通过Ajax从后端获取数据并在页面...
在前端开发中,经常需要循环JSON对象数组进行数据操作。使用...
AJAX(Asynchronous JavaScript and XML)是一种用于创建 We...
AJAX技术被广泛应用于现代Web开发,它可以在无需重新加载页面...
Ajax是一种通过JavaScript和HTTP请求交互的技术,可以实现无...