我有Asp.net Api这样获得JSON响应:
{\"UserID\":5,\"UserName\":\"asd\",\"Password\":\"asd\",\"Email\":\"ss@asd\",\"PhoneNumber\":\"1213\",\"Logtit\":0.0,\"Latitle\":0.0,\"OfGroup\":\"a \"}
如何使用Volley Lib在Android Studio中处理此JSON响应?
这是我的代码:
public class MainActivity extends AppCompatActivity {
RequestQueue requestqueue;
Button start;
TextView textView;
EditText ee;
public String givenValue = ee.getText().toString();
public String URL = "http://localhost:61511:8010/api/Feedback/5" ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestqueue=Volley.newRequestQueue(this);
final Button start =(Button)findViewById(R.id.btnget);
final TextView textView =(TextView)findViewById(R.id.mTextView);
final EditText ee =(EditText)findViewById(R.id.idtxt) ;
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("User");
for(int i= 0 ;i < jsonArray.length();i++){
JSONObject User = jsonArray.getJSONObject(i);
}
}catch (JSONException e ) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "ERROR");
}
}
);
requestqueue.add(jsonObjectRequest);}
});
}
答案 0 :(得分:1)
很可能您正在获得字符串响应。如果它是字符串,则首先将其转换为Json Object ..您可以按照以下步骤进行操作。
JSONObject jsonObject=new JSONObject(response);
如果已经是JSONObject,请尝试将其转换为java对象,如下所示:
int userId=jsonObject.getInt("UserID");
String userName=jsonObject.getString("UserName");
String pass=jsonObject.getString("Password");
将代码放入onResponse中。最后似乎您正在获取对象数组。然后创建一个POJO类,如下所示:
public class UserData {
@Expose
@SerializedName("UserId")
private int userId;
@Expose
@SerializedName("UserName")
private String userName;
.
.
.
//add the extra attribute and create getter and setter
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
然后在您的代码中声明:
ArrayList<UserData>userDataList=new ArrayList();
按照以下方法通过json数据解析将数据设置为arraylist
int userId=jsonObject.getInt("UserID");
String userName=jsonObject.getString("UserName");
String pass=jsonObject.getString("Password");
UserData userInfo=new UserData();
userInfo.setUserId(userId)
userIfo.setUserName(userName);
//add the other attribute similiarly
userDataList.add(userInfo);
答案 1 :(得分:0)
您可以使用GSON将其解析为Map。 有关更多信息,请参阅this问答。