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, -104.606667],
    "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();
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值