【问题标题】:Parsing a JSON object in Android在 Android 中解析 JSON 对象
【发布时间】:2015-11-26 02:33:56
【问题描述】:

我正在尝试解析一个如下所示的单个 JSON 对象:

{
  "message":"Request Successful",
  "data":{
    "id":"g8nEDt",
    "name":"Twins Bazil Twins",
    "nameDisplay":"Twins Bazil Twins",
    "abv":"6.75",
    "isOrganic":"N",
    "description":"Beers",
    }
  },
  "status":"success"
}

这是我正在使用的代码。

public class randomBeer  extends Activity {
TextView name1;
TextView description1;
TextView abv1;
TextView ibu1;
Button Btngetdata;

//URL to get JSON Array
    private static String urlRandom = "http://api.brewerydb.com/v2/beer/random?key=mykey";

//JSON Node Names
private static final String TAG_DATA = "data";
private static final String TAG_NAME = "name";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_ABV = "abv";
private static final String TAG_IBU = "ibu";

JSONObject data = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.randombeer);
    Btngetdata = (Button)findViewById(R.id.getdata);
    Btngetdata.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            new JSONParse().execute();

        }
    });

}

private class JSONParse extends AsyncTask<String, String, JSONObject> {
    private ProgressDialog pDialog;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        name1 = (TextView)findViewById(R.id.name);
        description1 = (TextView)findViewById(R.id.description);
        abv1 = (TextView)findViewById(R.id.abv);
        ibu1 = (TextView)findViewById(R.id.ibu);
        pDialog = new ProgressDialog(randomBeer.this);
        pDialog.setMessage("Getting Data ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();

    }

    @Override
    protected JSONObject doInBackground(String... args) {
        JSONParser jParser = new JSONParser();

        // Getting JSON from URL
        JSONObject json = jParser.getJSONFromUrl(urlRandom);
        return json;
    }
    @Override
    protected void onPostExecute(JSONObject json) {
        pDialog.dismiss();
        try {
            // Getting JSON Array
            data= json.getJSONArray(TAG_DATA);
            JSONObject c = data.getJSONObject(0);

            // Storing  JSON item in a Variable
            String name = c.getString(TAG_NAME);

            String ibu;

            if(c.has("ibu")) {
                ibu = c.getString(TAG_IBU);
            } else {
                ibu = "No ibu value";
            }

            String abv;

            if(c.has("abv")) {
                abv = c.getString(TAG_ABV);
            } else {
                abv = "No abv value";
            }

            String description;

            if(c.has("description")) {
                description = c.getString(TAG_DESCRIPTION);
            } else {
                description = "No description available";
            }


            //Set JSON Data in TextView
            name1.setText(name);
            description1.setText(description);
            abv1.setText(abv);
            ibu1.setText(ibu);

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}

}

问题是它试图获取一个数组,但我只需要和对象。 如何转换此代码以获取对象而不是尝试获取数组?

我试图改变

data = json.getJSONArray(TAG_DATA); 

data = json.getJSONObject(TAG_DATA);

然后就行了

JSONObject c = data.getJSONObject(0); 

我得到一个错误:

(87, 51) 错误:不兼容的类型:int 无法转换为 字符串。

【问题讨论】:

  • 您的示例“数据”也是 JSONObject,而不是 JSONArray。数组必须有 [...]

标签: android json parsing android-studio


【解决方案1】:

替换这个:

        // Getting JSON Array 
        data= json.getJSONArray(TAG_DATA);
        JSONObject c = data.getJSONObject(0);

与:

        // Getting JSON Object 
        data= json.getJSONObject(TAG_DATA);

另外,用“data”替换所有“c”变量用法。

【讨论】:

  • 完成。现在,当我运行我的应用程序时出现此错误:com.javapapers.android.jsonparsing W/System.err:org.json.JSONException: No value for data
  • 好的,假设您的数据模型说data 属性是可选的,那么您首先需要在调用getJSONObject() 之前检查data 属性是否存在(通过json.has(TAG_DATA)),并且然后做正确的事。查看已经在使用has() 的其他代码。
  • 但是它没有数据是没有意义的,因为它应该每次都给出那个值。
  • 您需要设置断点以查看您的实际数据,和/或您应该记录数据(JSONObject.toString() 可能会有所帮助)。这都是编程经验的一部分:-)。在任何情况下,您都应该始终尝试对您的代码进行防弹,这样任何“不应该发生”(但无论如何都会发生)的事情都不会导致您崩溃。世界不是一个完美的地方。
【解决方案2】:

应该是

data= json.getJSONObject(TAG_DATA);

而不是

data= json.getJSONArray(TAG_DATA);

在 onPostExecute 中。现在有

  "data":{
    "id":"g8nEDt",
    "name":"Twins Bazil Twins",
    "nameDisplay":"Twins Bazil Twins",
    "abv":"6.75",
    "isOrganic":"N",
    "description":"Beers",
    }

在里面。要获得即“名称”,请使用

 String name = data.getString("name");

另外:

确保在使用此链接时执行 HttpGet 而不是 HttpPost

http://api.brewerydb.com/v2/beer/random?key=mykey

【讨论】:

  • 完成。现在,当我运行我的应用程序时出现此错误:com.javapapers.android.jsonparsing W/System.err:org.json.JSONException: No value for data
  • 你确定你的 json 看起来像上图吗? @WardP
  • 是的,我确定。 url 总是从 api 返回随机啤酒。这是一个例子: { "message":"Request Successful", "data":{ "id":"WYLmep", "name":"Hasser\u00f6der Premium Pils", "nameDisplay":"Hasser\u00f6der Premium Pils" , "isOrganic":"N", "status":"verified", "statusDisplay":"Verified", "createDate":"2012-08-12 12:22:58", "updateDate":"2012-08 -17 18:34:09" }, "状态":"成功" }
  • 这个错误出现在哪一行?你调试过吗? @WardP
  • 发生在这一行:data= json.getJSONObject(TAG_DATA);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多