从Java中的JSON对象获取数组

时间:2017-02-04 22:49:57

标签: java android json

我将如何解析此JSON对象并在Android上使用Java获取“groups”数组。

{ "groups": [ "Total_Social_Beta_Testers", "Test_Group" ] }

这是我的代码:

LoginActivity.java

    Response.Listener<String> responseListener = new Response.Listener<String>() {


        @Override
        public void onResponse(String response) {
            try {
                JSONObject jsonResponse = new JSONObject(response);
                boolean success = jsonResponse.getBoolean("success");

                if (success) {
                    String username = jsonResponse.getString("username");
                    String email = jsonResponse.getString("email");
                    String gender = jsonResponse.getString("gender");
                    String country = jsonResponse.getString("country");
                    String verified = jsonResponse.getString("verified");
                    String avatar = jsonResponse.getString("avatar");
                    //String group = jsonResponse.getString("groups");

                    int numlength = 0;
                    int CI = 0;

                    JSONArray jsonArrayGR = jsonResponse.getJSONArray("groups");
                    //String array of 500 spots
                    String rows = "";

                    for (int i = 0; i < jsonArrayGR.length(); i++){
                        CI++;
                        rows = jsonArrayGR.getString(i);
                    }
                    //int rows = jsonResponse.getInt("rows");

                    //Starting Activity
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    intent. addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                    intent.putExtra("username", username);
                    intent.putExtra("email", email);
                    intent.putExtra("gender", gender);
                    intent.putExtra("country", country);
                    intent.putExtra("verified", verified);
                    intent.putExtra("avatar", avatar);
                    intent.putExtra("groups", rows);

                    //intent.putExtra("rows", rows);

                    session.createUserSession(
                            username,
                            email,
                            gender,
                            country,
                            verified,
                            avatar,
                            rows
                    );

                    Toast.makeText(getBaseContext(), "Login succeed, welcome!" , Toast.LENGTH_LONG).show();

                    //Adding a new flag to start the activity
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    LoginActivity.this.startActivity(intent);
                    _loginButton.setEnabled(true);
                    finish();

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

    };
    LoginRequest loginRequest = new LoginRequest(e, password, responseListener);
    RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
    queue.add(loginRequest);

UserSession.java

 public void createUserSession(
        String name,
        String email,
        String gender,
        String country,
        String verified,
        String avatar,
        String groups){

    //Storage_Start session
    editor.putBoolean(IS_USER_LOGIN, true);

    // Storing name in pref
    editor.putString(KEY_NAME, name);

    //Storage of the email in pref
    editor.putString(KEY_EMAIL, email);

    //Storing the gender
    editor.putString(KEY_GENDER, gender);

    //Storing the country
    editor.putString(KEY_COUNTRY, country);

    //Storing the verified
    editor.putString(KEY_VERIFIED, verified);

    //Storing avatar
    editor.putString(KEY_AVATAR, avatar);

    //Storing groups
    editor.putString(KEY_GROUPS, groups);

    //Storing the gRows
    //editor.putInt(INT_GROUPS, numlength);

    //commit changes
    editor.commit();
}




/**
 * Get stored session data
 * */
public HashMap<String, String> getUserDetails(){

    //Use hashmap to store user credentials
    HashMap<String, String> user = new HashMap<String, String>();

    // user name
    user.put(KEY_NAME, pref.getString(KEY_NAME, null));

    // user email id
    user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));

    //gender
    user.put(KEY_GENDER, pref.getString(KEY_GENDER, null));

    //country
    user.put(KEY_COUNTRY, pref.getString(KEY_COUNTRY, null));

    //verifed?
    user.put(KEY_VERIFIED, pref.getString(KEY_VERIFIED, null));

    //Avatar
    user.put(KEY_AVATAR, pref.getString(KEY_AVATAR, null));

    //Groups
    user.put(KEY_GROUPS, pref.getString(KEY_GROUPS, null));

    // return user
    return user;
}

更新 这是我将值存储到recyclerview中的地方:

public class ChatsAdapter extends RecyclerView.Adapter<ChatsAdapter.MyViewHolder> {
private List<Groups> chatlist;

public class MyViewHolder extends RecyclerView.ViewHolder {
    public TextView group;

    public MyViewHolder(View view) {
        super(view);
        group = (TextView) view.findViewById(R.id.groups);
    }
}

public ChatsAdapter(List<Groups> chatlist){
    this.chatlist = chatlist;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType)    {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.chat_row_list, parent, false);

    return new MyViewHolder(itemView);
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    Groups groups = chatlist.get(position);
    holder.group.setText(groups.getTitle());
}

@Override
    public int getItemCount() {
        return chatlist.size();
   }
}

这就是我定义字符串的方式:

 public class Groups {
    private String groups = "";

    public Groups() {
    }

     public Groups(String groups) {
         this.groups = groups;
     }

     public String getTitle() {
         return groups;
     }
   }

这是我在主要活动中显示适配器(上面)设置的值的方式:

    //groups
    String g = user.get(UserSessionManager.KEY_GROUPS);

    String numrows = user.get(UserSessionManager.INT_GROUPS);

    //String grows = user.get(UserSessionManager.INT_GROUPS);


    int rows = Integer.parseInt(numrows);

    Groups groups = new Groups(g);
    groupslist.add(groups);


    chatsAdapter.notifyDataSetChanged();

4 个答案:

答案 0 :(得分:0)

您应该使用此ArrayList<String>生成JSONArray并使用此List填充RecyclerView

 ArrayList<String> listdata = new ArrayList<String>();
 if (jArray != null) { 
     for (int i=0;i<jArray.length();i++)
           listdata.add(jsonArrayGR.getString(i));
 } 

现在,您可以将此List发送到MainActivity并填写您需要的RecyclerView

In current Activity ->

Bundle extra = new Bundle();
extra.putSerializable("list", listdata);

Intent intent = new Intent(getBaseContext(), MainActivity.class);
intent.putExtra("extra", extra);

In Mainactivity ->

Bundle extra = getIntent().getBundleExtra("extra");
ArrayList<Object> objects = (ArrayList<Object>) extra.getSerializable("objects")

答案 1 :(得分:0)

在app.gradle中

,在依赖项下添加此行

import React from "react"
import { connect } from "react-redux"
import { fetchUser } from "../actions/userActions"
import { fetchTweets } from "../actions/tweetsActions"
import { deleteTweet } from "../actions/tweetsActions"

@connect((store) => {
  return {
    user: store.user.user,
    userFetched: store.user.fetched,
    tweets: store.tweets.tweets,
  };
})

export default class Layout extends React.Component {
  componentWillMount() {
    this.props.dispatch(fetchUser())
    this.props.dispatch(fetchTweets())
  }

  fetchTweets() {
    //this.props.dispatch(fetchTweets())
  }

  deleteTweet(idx, e) {
    this.props.dispatch(deleteTweet(idx))
  }

  render() {
    const { user, tweets, i } = this.props;
    //console.log(this.props)
    const mappedTweets = tweets.map((tweet, i) => <li key={i}>{tweet.text}<button onClick={this.deleteTweet.bind(this, i)}>delete</button></li>)

    return <div>
      <h1>{user.name}</h1>
      <ul>{mappedTweets}</ul>
    </div>
  }
}

并同步您的项目。

现在创建一个名为 GroupsModal.java的 .java 文件
将其添加到 GroupsModal.java文件

compile 'com.google.code.gson:gson:2.3'

现在创建一个名为 Groups.java .java 文件,并添加以下行:

private Groups groups;

//getters and setters

现在位于 loginActivity.java

private String Total_Social_Beta_Testers;
//getters and setters

希望有所帮助......

答案 2 :(得分:0)

&#13;
&#13;
String[] getStringArray(String name, JSONObject object) throws JSONException {
  JSONArray jsonArray = object.getJSONArray(name);
  String[] array = new String[jsonArray.length()];
  for (int i = 0; i < jsonArray.length(); i++){
    array[i] = jsonArray.getString(i);
  }
  return array;
}
&#13;
&#13;
&#13;

答案 3 :(得分:0)

我相信你必须面对问题

 for (int i = 0; i < jsonArrayGR.length(); i++){
                        CI++;
                        rows = jsonArrayGR.getString(i);
                    }

这是因为你没有在每个循环中追加行值,而是在编写先前的值。
简易解决方案

rows = jsonArrayGR.getString(i)+rows;

最佳解决方案

StringBuilder rows = new StringBuilder();

                    for (int i = 0; i < jsonArrayGR.length(); i++){
                        CI++;
                        rows.append(jsonArrayGR.getString(i));
                    }

最后在你的代码中使用它

intent.putExtra("groups", rows);

P.S。如果您想稍后将行用作String,只需使用
String rows = rows.toString();

我希望这肯定能帮助你:D