【问题标题】:Extracting JSONObject fromJSONArray从 JSON 数组中提取 JSON 对象
【发布时间】:2018-08-09 16:52:11
【问题描述】:

在一个 android 应用程序上工作以尝试连接到“steemit.com”并将 JSON 数据返回给我。

到目前为止一切正常,将大量响应从 URL 打印到 Textview,只是我现在没有收到任何错误,屏幕上也没有打印出任何文本,所以我假设我使用了错误类型的对象或其他东西.也许我要检索的数据不是数组?大家怎么看?这是我的代码。

    public class fetchdata extends AsyncTask<Void,Void,Void> {

    String data = "";
    String dataParsed = "";
    String singleParsed = "";

    @Override
    protected Void doInBackground(Void... voids) {


        {
            try {
                URL url = new URL("https://steemit.com/@curie.json");

                HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
                InputStream inputStream = httpsURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

                String lines = "";
                while(lines != null){
                    lines = bufferedReader.readLine();
                    data = data + lines;
                }

                JSONArray JA = new JSONArray(data);
                for (int i =0 ;i < JA.length(); i++){
                    JSONObject JO = (JSONObject) JA.get(i);
                    singleParsed = "User: " + JO.get("user") + "\n" +
                                    "Location: " + JO.get("location") + "\n" +
                                    "ID: " + JO.get("id")+"\n";

                    dataParsed = dataParsed + singleParsed;
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);

        followers.dataTV.setText(this.dataParsed);


    }


}

以及我希望 TextView 显示数据的页面。

    public class followers extends AppCompatActivity {
    public static TextView dataTV;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_followers);

        ListView followList = (ListView)findViewById(R.id.followList);
        dataTV = (TextView)findViewById(R.id.followersTVData);

        fetchdata process = new fetchdata();
        process.execute();


    }
}

如果我不清楚,问题是什么,当我使用变量 'data' 'printText' 时,没有问题,并且打印了批量文本,但是,我现在试图打破它下降到位,当我使用变量'dataParsed'时它只是不打印任何东西。任何帮助表示赞赏。提前谢谢!

我被要求回复。在这里,虽然很长。

{"user":{"id":1026971,"name":"ceruleanblue","owner":{"weight_threshold":1,"account_auths":[],"key_auths":[["STM7UPr1LJMw4aAxcuiYAmad6bjjiaeDcfgSynRMrr5L6uvuSJLDJ",1]]},"active":{"weight_threshold":1,"account_auths":[],"key_auths":[["STM7qUaQCghsFZA37fTxVB4BqBBK49z35ni6pha1Kr4q4qLkrNRyH",1]]},"posting":{"weight_threshold":1,"account_auths":[["minnowbooster",1],["steemauto",1]],"key_auths":[["STM7qF27DSYNYjRu5Jayxxxpt1rtEoJLH6c1ekMwNpcDmGfsvko6z",1]]},"memo_key":"STM7wNQdNS9oPbVXscbzn7vfzjB7SwmLGQuFQNzZgatgpqvdKzWQZ","json_metadata":{"profile":{"profile_image":"https://cdn.steemitimages.com/DQmfNj7SLU1aBtV9UkJa5ZKMZPNuzR4ei5UJRA54JxFk99M/Mushrooms%20Trippy%20Art%20Fabric%20Cloth%20Rolled%20Wall%20Poster%20Print.jpg","name":"Cerulean's Chillzone","about":"IT Technician, Programmer, Day Trader, Night Toker.","location":"Ontario, Canada","cover_image":"https://cdn.steemitimages.com/DQmTwT379V7EcQ1ZkqkmJkpWyu4QXw1LzDinv9uoyixksMY/tumblr_static_tumblr_static__640.jpg"}},"proxy":"","last_owner_update":"2018-06-18T19:57:39","last_account_update":"2018-08-01T04:33:06","created":"2018-06-03T20:28:21","mined":false,"recovery_account":"steem","last_account_recovery":"1970-01-01T00:00:00","reset_account":"null","comment_count":0,"lifetime_vote_count":0,"post_count":321,"can_vote":true,"voting_power":9800,"last_vote_time":"2018-08-09T02:47:03","balance":"8.000 STEEM","savings_balance":"0.000 STEEM","sbd_balance":"1.979 SBD","sbd_seconds":"927621285","sbd_seconds_last_update":"2018-08-09T13:23:15","sbd_last_interest_payment":"2018-07-11T10:18:12","savings_sbd_balance":"0.000 SBD","savings_sbd_seconds":"2067163545","savings_sbd_seconds_last_update":"2018-07-23T08:58:48","savings_sbd_last_interest_payment":"2018-07-09T06:32:27","savings_withdraw_requests":0,"reward_sbd_balance":"0.000 SBD","reward_steem_balance":"0.000 STEEM","reward_vesting_balance":"0.000000 VESTS","reward_vesting_steem":"0.000 STEEM","vesting_shares":"167703.513691 VESTS","delegated_vesting_shares":"29412.000000 VESTS","received_vesting_shares":"0.000000 VESTS","vesting_withdraw_rate":"0.000000 VESTS","next_vesting_withdrawal":"1969-12-31T23:59:59","withdrawn":0,"to_withdraw":0,"withdraw_routes":0,"curation_rewards":182,"posting_rewards":110408,"proxied_vsf_votes":[0,0,0,0],"witnesses_voted_for":1,"last_post":"2018-08-07T12:43:42","last_root_post":"2018-08-07T12:25:39","average_bandwidth":"44620566375","lifetime_bandwidth":"1099256000000","last_bandwidth_update":"2018-08-09T13:23:15","average_market_bandwidth":3415484305,"lifetime_market_bandwidth":"237250000000","last_market_bandwidth_update":"2018-08-07T13:21:39","vesting_balance":"0.000 STEEM","reputation":"1564749115439","transfer_history":[],"market_history":[],"post_history":[],"vote_history":[],"other_history":[],"witness_votes":["guiltyparties"],"tags_usage":[],"guest_bloggers":[]},"status":"200"}null

也许我执行不当?

            for (int i =0 ;i < JA.length(); i++){
                JSONObject JO = (JSONObject) JA.getJSONObject(i);
                singleParsed = "User: " + JO.get("user.id") + "\n" +
                                "Location: " + JO.get("location") + "\n" +
                                "ID: " + JO.get("id")+"\n";

                dataParsed = dataParsed + singleParsed;
            }

更新的修复,仍然有问题,但更进一步。

            String lines = "";
            while(lines != null){
                lines = bufferedReader.readLine();
                data = data + lines;
            }

            JSONObject JO = new JSONObject(data);
            String m = "";
            for (int i =0 ;i < JO.length(); i++){
//                    JSONObject JO = (JSONObject) JO.getJSONObject(i);
                singleParsed = "User: " + JO.getString("user.id") + "\n" +
                                "Location: " + JO.getString("location") + "\n" +
                                "ID: " + JO.getString("id")+"\n";

                dataParsed = dataParsed + singleParsed;

DEBUGGER BREAKS ON "singleParsed = "user:",这里有什么想法吗?

【问题讨论】:

  • 你能发布回复吗?
  • 哈哈,你要求它:) 上面添加了响应。不幸的是,调试器显示在 FOR 循环期间绝对没有记录任何数据。

标签: java android json android-studio


【解决方案1】:

JSONArray 对象有一个函数 getJSONObject(int index),你可以通过编写一个简单的 for 循环来遍历所有 JSONObjects:

JSONArray 数组;

for(int n = 0; n < array.length(); n++)
{
    JSONObject object = array.getJSONObject(n);
    int id = object.getInt("id");
    String species = object.getString("species");
    String name = object.getString("name");
}

试试这个

【讨论】:

  • 这看起来很完美,但还是不行。也许我实施错了?我将在我的帖子底部添加代码
  • 实际上我看到了您的回复您的回复在您的 json 中包含字典您必须获取像这样的值 stackoverflow.com/questions/28736419/…
【解决方案2】:

响应是 JSONObject 而不是 JSONArray
因此,您可以在代码中直接使用:new JSONObject(data);

另外,你还没有注意到,在右大括号的末尾有一个null

【讨论】:

  • 我以为我摆脱了那些空值!谢谢!重启!
【解决方案3】:

我认为您应该使用 JSONObject 解析数据,因为响应不是数组。您应该创建包含 User 类和 String 的类来处理响应的状态。

或者您可以改用改造。 http://square.github.io/retrofit/

【讨论】:

  • 我在想这个,会再试一次。谢谢!
【解决方案4】:

试试这个……

    try {
            JSONObject object = new JSONObject(data);
            String user = object.getString("user");
            int id = user.getInt("id");
            String name = user.getString("name"); 
            String owner = user.getString("owner");
            int weight_threshold = owner.getInt("weight_threshold");
            JSONArray account_auths = owner.getJSONArray("account_auths");   
.....        
        } catch (Exception e) {
           e.printStackTrace();
        }

传递其他对象等等。

【讨论】:

    猜你喜欢
    • 2019-03-22
    • 2019-09-20
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-27
    • 1970-01-01
    相关资源
    最近更新 更多