[转载]Android上解析Json格式数据(一)

[转载]Android上解析Json格式数据(一) – 淡如雪 – 博客园.

最近发现在做解析数据时,用到Json这种格式去解析数据挺方便,也得到不少人的青睐,下面是我个人总结的一些Json用法以及用列

/*
 * Json 一.Json主要是以键值对的形式存储数据的 ,Json描述很简单 {"name":"zhenhua","age":"23"}
 * 表示一个Json对象 [{"name":"zhenhua","age":"23"}]中括号表示Json对象的数组
 * [{"name":"zhenhua","age":"23"},{"name":"zhenhua","age":"23"}] 1.开始解析数组
 * 2.开始解析对象 3.开始解析键值对2 4.开始解析键值对 5.解析对象结束 6.开始解析对象 7.开始解析键值对 8.开始解析键值对 9.解析对象结束
 * 10.解析数组结束 二:如何把Json数组转换成java对象 String
 * date=[{"name":"zhenhua","age":"23"},{"name":"zhenhua","age":"23"}]
 */

 

public class Json extends Activity {
 String TAG = "Json message";

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  detectJSON();
 }

 private void detectJSON() {
  String str = "{"
    + "\"日期\" : \"2011-06-06\","
    +
    // Like 是 JSONObject
    "\"Like\" : {" + "\"Name\" : \"加内特\","
    + "\"Height\" : \"2.11cm\"," + "\"Age\" : 35"
    + "},"
    +
    // LikeList 就是一个 JSONObject
    "\"LikeList\":" + "{\"List\": "
    + "["
    +
    // 这里也是JSONObject
    "{" + "\"Name\" : \"Rose\"," + "\"Height\" : \"190cm\","
    + "\"Age\" : 23" + "},"
    +
    // 这里也是JSONObject
    "{" + "\"Name\" : \"科比\"," + "\"Height\" : \"198cm\","
    + "\"Age\" : 33" + "}" + "]" + "}" + "}";
  try {

   JSONObject dataJson = new JSONObject(str);
   Log.d(TAG, dataJson.getString("日期"));

   JSONObject nbaJson = dataJson.getJSONObject("Like");
   Log.d(TAG, nbaJson.getString("Name"));
   Log.d(TAG, nbaJson.getString("Height"));
   Log.d(TAG, nbaJson.get("Age").toString());

   JSONObject listJson = dataJson.getJSONObject("LikeList");
   JSONArray arrayJson = listJson.getJSONArray("List");
   for (int i = 0; i < arrayJson.length(); i++) {
    JSONObject tempJson = arrayJson.optJSONObject(i);
    Log.d(TAG, tempJson.getString("Name"));
    Log.d(TAG, tempJson.getString("Height"));
    Log.d(TAG, tempJson.getString("Age").toString());
   }
  } catch (JSONException e) {
   System.out.println("Something wrong...");
   e.printStackTrace();

  }

 }
}
赞(0) 打赏
分享到: 更多 (0)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏