2013-03-18 62 views
0

我在线学习了一个教程,并调整了一些代码,我希望应用程序从不同位置读取信息。目前该应用程序正在正确读取来自here的数据。现在我想从here读取数据。我期望获得观察时间,Temp_C &可见性,我想我需要在try {括号内更改我的代码以读取此数据?有什么建议么?如何解析JSON数据到Android?

public class MainActivity extends ListActivity { 

// url to make request 
private static String url = "http://api.androidhive.info/contacts/"; 

// JSON Node names 
private static final String TAG_DATA = "contacts"; 
private static final String TAG_OBSERV = "name"; 
private static final String TAG_TEMP = "email"; 
private static final String TAG_VISIB = "gender"; 

// contacts JSONArray 
JSONArray contacts = null; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    // Hashmap for ListView 
    ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>(); 

    // Creating JSON Parser instance 
    JSONParse jParser = new JSONParse(); 

    // getting JSON string from URL 
    JSONObject json = jParser.getJSONFromUrl(url); 

    try { 
     // Getting Array of Contacts 
     contacts = json.getJSONArray(TAG_DATA); 

     // looping through All Contacts 
     for(int i = 0; i < contacts.length(); i++){ 
      JSONObject c = contacts.getJSONObject(i); 

      // Storing each json item in variable 
      String name = c.getString(TAG_OBSERV); 
      String email = c.getString(TAG_TEMP); 
      String gender = c.getString(TAG_VISIB); 

      // creating new HashMap 
      HashMap<String, String> map = new HashMap<String, String>(); 

      // adding each child node to HashMap key => value 
      map.put(TAG_OBSERV, name); 
      map.put(TAG_TEMP, email); 
      map.put(TAG_VISIB, gender); 

      // adding HashList to ArrayList 
      contactList.add(map); 
     } 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 

    // Updating parsed JSON data into ListView 
    ListAdapter adapter = new SimpleAdapter(this, contactList, 
      R.layout.list_item, 
      new String[] { TAG_OBSERV, TAG_TEMP, TAG_VISIB }, new int[] { 
        R.id.name, R.id.email, R.id.mobile }); 

    setListAdapter(adapter); 

    // selecting single ListView item 
    ListView lv = getListView(); 

    // Launching new screen on Selecting Single ListItem 
    lv.setOnItemClickListener(new OnItemClickListener() { 

     public void onItemClick(AdapterView<?> parent, View view, 
       int position, long id) { 
      // getting values from selected ListItem 
      String name = ((TextView) view.findViewById(R.id.name)).getText().toString(); 
      String cost = ((TextView) view.findViewById(R.id.email)).getText().toString(); 
      String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString(); 

      // Starting new intent 
      Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class); 
      in.putExtra(TAG_OBSERV, name); 
      in.putExtra(TAG_TEMP, cost); 
      in.putExtra(TAG_VISIB, description); 
      startActivity(in); 
     } 
    }); 
} 

}

+0

请将您的代码降低到最低程度。一般来说,你可以用'outer.getJSONObject(“name”)''读取*子对象*(像''name':{...}'')。 – rekire 2013-03-18 18:25:56

回答

0

如何解析JSON数据到Android?

所以起初你应该把你的代码移动到你试图从网络连接(从JSON获取数据)到后台线程的地方。实际上你在Main(UI)线程中执行它,它不是很好,也不正确。如果您的应用程序将安装在运行Android 3.0或更高版本的设备上,您将获得NetworkOnMainThreadException,这并不好,不是吗?

其次,保存您的JSON并进行一些格式化以更好地查看其结构。 Multiset括号{表示JSONObject和括号[表示JSONArray。

现在你应该能够解析JSON。现在我写你一小段代码如何开始:

JSONObject o = new JSONObject(sourceString); 
if (o != null) { 
    JSONObject data = o.getJSONObject("data"); // getting JSONObject with key data 
    if (data != null) { 
     JSONArray current = data.getJSONArray("current_condition"); 
    } 
} 
... 
0

这里是你应该分析和从该JSON让您的值的方式:

JSONObject mMainObject = new JSONObject(myResponseString); 
if(mMainObject != null){ 
    JSONObject data = mMainObject.getJSONObject("data"); 
    if(data != null){ 
     JSONArray currentCondition = data.getJSONArray("current_condition"); 
     if(currentCondition != null){ 
      for(int i = 0; i < currentCondition.lenght(); i++){ 
       JSONObject obj = currentCondition.get(i); 
       if(obj != null){ 
        String observation_time = obj.getString("observation_time"); 
        String temp_C = obj.getString("temp_C"); 
        String visibility = obj.getString("visibility"); 
       } 
      } 
     } 
    } 
} 

这样做,你应该考虑适当的方式从互联网上下载的数据使用AsyncTask例如。通过这种方式,它不会阻止你的用户界面,并且你的应用会更加快速响应。

希望得到这个帮助! :)

+0

如果有多个数组需要从JSON文件中检索,我们不需要使用FOR循环吗? – Si8 2013-11-08 22:11:15

0

的最简单和最漂亮的方式是创建一个DTO与想要的属性,然后使用一个库如杰克逊GSON映射JSON来(多个)对象。然后它将是2行代码,而不是“手动解析”。