【问题标题】:How to access invidual json objects from a json array?如何从 json 数组访问单个 json 对象?
【发布时间】:2015-07-13 17:38:44
【问题描述】:

我有以下回复,我想在个人TextView 中显示所有eqid,但我不知道如何实现这一点, 下面是我从服务器获取数据并在 textview 中显示的 sn-p 代码和响应。
谁能帮我解决这个问题?

{
  "earthquakes":[
    {
      "eqid":"c0001xgp",

    },
    {
      "eqid":"c000905e",

    },
    {
      "eqid":"2007hear",

    },
    {
      "eqid":"c00090da",

    },
    {
      "eqid":"2007aqbk",

    },
    {
      "eqid":"2007hec6",

    },
    {
      "eqid":"a00043nx",

    },
    {
      "eqid":"2010utc5",

    },

  ]
}

代码

   ServiceHandler sh = new ServiceHandler();
    jsonStr = sh.makeServiceCall(USER_URL, ServiceHandler.GET);
    Log.d("Response: ", "> " + jsonStr);

    try{
        JSONObject json = new JSONObject(jsonStr);
        JSONArray items = json.getJSONArray("product");

        parent_layout = (RelativeLayout)findViewById(R.id.rl);
        for(int i =0; i<items.length(); i++){



            TextView textView = new TextView(this);
            textView.setText(items.getJSONObject(i).getString(USER_NAME));

            parent_layout.addView(textView);
        }

【问题讨论】:

    标签: android json jsonobject


    【解决方案1】:

    try{
        JSONObject json = new JSONObject(jsonstr);
        JSONArray items = json.getJSONArray("earthquakes");
    
        for(int i =0; i<items.length(); i++){
            TextView t=new TextView(context);
            t.setText(items.getJSONObject(i).getString('eqid'));
            ParentLayout.addView(t);
        }
    }catch(JSONException e){
        e.printStacktrace();
    }

    【讨论】:

    • 查看我编辑的有问题的代码..我没有任何错误..但没有显示响应
    • 当您使用相对布局时,您的文本视图将相互重叠...尝试线性布局或添加 layoutToLeftOf 或 above 或 below 等属性......
    【解决方案2】:

    您有一个包含单个 JSON 数组的 JSON 对象。因此,您首先从对象中检索数组,然后您可以遍历它以检索所有项目。在下面的代码中,我假设您在一个数组中有指定的 TextView 对象。

    try{
        JSONObject json = new JSONObject(jsonstr);
        JSONArray items = json.getJSONArray("earthquakes");
    
        for(int i =0; i<items.length(); i++){
            textViews[i].setText(items.getJSONObject(i).getString('eqid'));
        }
    }catch(JSONException e){
        e.printStacktrace();
    }
    

    【讨论】:

    • 你能说一件事吗??
    • stackoverflow.com/questions/18917214/… 这个问题他们改变颜色..我可以添加按钮交替
    • 那将是一个单独的问题。问题应围绕主题。
    • 数组类型预期找到 android 小部件 textview..它显示
    • @Roman 在我的回答中,我声明我假设目标 TextView 对象在一个数组中,因此可以在循环中像 textViews[i] 一样引用。如果textView 变量没有引用TextView 数组,您将收到此错误。我假设您知道在哪里可以找到要放置数据的TextViews
    猜你喜欢
    • 1970-01-01
    • 2021-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    相关资源
    最近更新 更多