Android上解析Json格式数据
2013-07-31 09:56 @疯狂的迈步 阅读(203) 评论(0) 编辑 收藏 举报1 package com.practice.json; 2 3 import org.json.JSONArray; 4 import org.json.JSONException; 5 import org.json.JSONObject; 6 7 import android.app.Activity; 8 import android.os.Bundle; 9 import android.util.Log; 10 11 public class JsonDemo extends Activity { 12 /* 13 * 解析JSON的例子,str保存的是JSON代码,解析后的数据在LogCat里输出 14 */ 15 16 String TAG = "Json message"; 17 18 @Override 19 public void onCreate(Bundle savedInstanceState) { 20 super.onCreate(savedInstanceState); 21 setContentView(R.layout.main); 22 detectJSON(); 23 } 24 25 private void detectJSON() { 26 String str = "{"+ 27 28 "\"日期\" : \"2011-06-06\","+ 29 30 //Like 是 JSONObject 31 "\"Like\" : {"+ 32 "\"Name\" : \"加内特\","+ 33 "\"Height\" : \"2.11cm\","+ 34 "\"Age\" : 35"+ 35 "},"+ 36 37 //LikeList 就是一个 JSONObject 38 "\"LikeList\":" + 39 "{\"List\": " + 40 "["+ 41 //这里也是JSONObject 42 "{"+ 43 "\"Name\" : \"Rose\","+ 44 "\"Height\" : \"190cm\","+ 45 "\"Age\" : 23"+ 46 "},"+ 47 //这里也是JSONObject 48 "{"+ 49 "\"Name\" : \"科比\","+ 50 "\"Height\" : \"198cm\","+ 51 "\"Age\" : 33"+ 52 "}"+ 53 "]"+ 54 "}"+ 55 "}"; 56 57 try { 58 JSONObject dataJson = new JSONObject(str); 59 Log.d(TAG, dataJson.getString("日期")); 60 61 JSONObject nbaJson = dataJson.getJSONObject("Like"); 62 63 Log.d(TAG, nbaJson.getString("Name")); 64 Log.d(TAG, nbaJson.getString("Height")); 65 Log.d(TAG, nbaJson.get("Age").toString()); 66 67 JSONObject listJson = dataJson.getJSONObject("LikeList"); 68 JSONArray arrayJson = listJson.getJSONArray("List"); 69 70 for(int i=0;i<arrayJson.length();i++) { 71 72 JSONObject tempJson = arrayJson.optJSONObject(i); 73 74 Log.d(TAG, tempJson.getString("Name")); 75 Log.d(TAG, tempJson.getString("Height")); 76 Log.d(TAG, tempJson.getString("Age").toString()); 77 } 78 79 80 } catch (JSONException e) { 81 System.out.println("Something wrong..."); 82 e.printStackTrace(); 83 } 84 } 85 }
测试代码通过
Add following code to AndroidManifest.
<instrumentation android:name="android.test.InstrumentationTestRunner"
android:targetPackage="your.package"
android:label="your tests label" />
<uses-library android:name="android.test.runner" />
- Right click project on Project Explorer Panel on Eclipse, then click "Run" > "Run Configurations...", then select "android.test.InstrumentationTestRunner" in Instrumentation TestRunner.
does not declare uses-library android.test.runner
在平时Android开发时突然执行程序,出现了 Application does not specify a
android.test.InstrumentationTestRunner instrumentation or does not declare
uses-library android.test.runner的错误提示,这主要是你再Run As中错误的选择了目标为Android JUnit
Test这项导致的,解决的方法也很简单在Run Dialog中删除JUnit Test这条即可。
END
---------------------------------------------------------------------------------------------
欢迎关注 我的微博@疯狂的迈步 我的github@junhey