淡如雪

导航

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();

  }

 }
}

posted on 2012-03-18 15:10  淡如雪  阅读(596)  评论(2编辑  收藏  举报