从JSONArray提取JSONObject

时间:2018-08-09 16:52:11

标签: java android json android-studio

在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;

在“ singleParsed =”用户:”上的调试中断,从这里有什么想法吗?

4 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

JSONArray对象具有getJSONObject(int index)函数,您可以通过编写简单的for循环遍历所有JSONObject:

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");
}

尝试一下

答案 2 :(得分:0)

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

此外,正如您所没有注意到的,在右括号后面有一个null

答案 3 :(得分:0)

尝试一下...

    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();
        }

传递其他对象,依此类推。