【问题标题】:How to parse single json object in android如何在android中解析单个json对象
【发布时间】:2016-12-08 10:10:57
【问题描述】:

我是 android 和 JSON 的新手。 我正在尝试获取 JSON 数据(以下):

{ "user": [ { "id": "001", "name": "Raj Amal", "email": "raj.amalw@gmail.com" } ] }

并在其中一个 android 应用程序文本视图中使用其数据。 那么我该如何处理上述问题。

我已经尝试了下面的代码,但它给出了异常。 请帮忙。谢谢

    {
    try{
            JSONObject obj=new JSONObject(jsonString);
            //Log.i(TAG,obj.getString(TAG_ID));
            String iid = obj.getString(TAG_ID);
            Log.i(TAG,iid);
            final TextView CardBalanceID = (TextView) findViewById(R.id.CardBalanceID);
            CardBalanceID.setText(iid);

       }catch(JSONException e){
        Log.i(TAG,"EXCEPTION");
        e.printStackTrace();}
}

【问题讨论】:

  • 考虑使用 gson 库...您上面的内容可能没问题,例如您正在展示,但随着 json 变得更加复杂,并不能真正扩展

标签: android json android-studio


【解决方案1】:

您的 id 对象位于 user 数组中。因此,您首先需要解析该数组。请尝试以下代码。

 try{
        JSONObject obj=new JSONObject(jsonString);
        JSONArray jArray = obj.getJSONArray("user");
        String iid = jArray.getJSONObject(0).getString(TAG_ID);
        Log.i(TAG,iid);
        final TextView CardBalanceID = (TextView) findViewById(R.id.CardBalanceID);
        CardBalanceID.setText(iid);

    }catch(JSONException e){
        Log.i(TAG,"EXCEPTION");
        e.printStackTrace();}


}

【讨论】:

  • 很高兴为您提供帮助 :) 在这里,我们将答案标记为正确,从而解决了我们的问题。
  • 我已经标记了。感谢您的信息。不知道(我是 SO 的新手)。
【解决方案2】:

我已经更新了你的代码试试这个。

 {
        try{
                JSONObject obj=new JSONObject(jsonString);
                //Log.i(TAG,obj.getString(TAG_ID));
                JSONArray jsnArry = obj.getJSONArray("user");
                // if you have more than 1 object in Array 
                // then loop is needed otherwise you can use directly 0th item.
                for(int i=0;i<jsnArry.length();i++){ 
                    JSONObject jsnObj = jsnArray.getJSONObject(i);
                    String iid = jsnObj .getString(TAG_ID);
                }

                Log.i(TAG,iid);
                final TextView CardBalanceID = (TextView) findViewById(R.id.CardBalanceID);
                CardBalanceID.setText(iid);

           }catch(JSONException e){
            Log.i(TAG,"EXCEPTION");
            e.printStackTrace();}
    }

【讨论】:

    猜你喜欢
    • 2011-07-30
    • 1970-01-01
    • 2017-08-20
    • 1970-01-01
    • 2015-11-26
    • 1970-01-01
    • 1970-01-01
    • 2016-02-17
    • 1970-01-01
    相关资源
    最近更新 更多