将json解析为android内部的字符串parseNetwork <string>

时间:2017-12-17 12:30:57

标签: android json android-volley

我有一个用于注册学生的web api,在我发布学生后它返回了他的id,我想将这个id从json解析为字符串并存储在变量中供以后使用,响应以这种形式表示1234指示用户id没有&#34;&#34; 这是我的代码

 try {
                            RequestQueue requestQueue = Volley.newRequestQueue(Register.this);
                            String URL = "http://192.168.0.148/WebApplication7/api/users";
                            JSONObject jsonBody = new JSONObject();
                            jsonBody.put("tblRegisteredUsers_UserName", userName.getText().toString().trim());
                            jsonBody.put("tblRegisteredUsers_FirstName", firstName.getText().toString());
                            jsonBody.put("tblRegisteredUsers_SecondName", secondName.getText().toString());
                            jsonBody.put("tblRegisteredUsers_LastName", familyName.getText().toString());
                            jsonBody.put("tblRegisteredUsers_Country", nationality.toString());
                            jsonBody.put("tblRegisteredUsers_MobileNumber", mobileNo.getText().toString());
                            jsonBody.put("tblRegisteredUsers_Email", email.getText().toString());
                            jsonBody.put("tblRegisteredUsers_Nationality", nationality.toString());
                            jsonBody.put("tblRegisteredUsers_Active", "false");
                            jsonBody.put("tblRegisteredUsers_PayType", saved_payment_type.toString());
                            jsonBody.put("tblRegisteredUsers_DraftInfo", saved_payment_type.toString());
                            jsonBody.put("tblRegisteredUsers_AccountStates", "pending");
                            jsonBody.put("tblRegisteredUsers_Password", encrypt(password.getText().toString()));
                            jsonBody.put("tblRegisteredUsers_registrationDate", DateFormat.getDateTimeInstance().format(new Date()).toString());
                            jsonBody.put("tblRegisteredUsers_nickName", userName.getText().toString().trim());
                            jsonBody.put("tblRegisteredUsers_Activeby_FKID", "-1");
                            jsonBody.put("tblRegisteredUsers_Year", "1");
                            jsonBody.put("tblRegisteredUsers_ActivebyPayment", "false");
                            jsonBody.put("tblRegisteredUsers_intensified", contract_Type.toString());


                            final String requestBody = jsonBody.toString();

                            StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {

                                        if (response.equals("success")) {
                                            //login authenticated. Start the next activity of your app
                                            Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
                                            // Toast.makeText(getApplicationContext(), "registered successfully ", Toast.LENGTH_SHORT).show();


                                        } else {
                                            //login failed. prompt to re-enter the credentials
                                             Toast.makeText(Register.this, "Failed to log In", Toast.LENGTH_SHORT).show();

                                            // Log.i("VOLLEY", response);
                                            Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
                                        }
                                    }
                            }, new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError error) {
                                    Log.e("VOLLEY", error.toString());
                                }
                            }) {
                                @Override
                                public String getBodyContentType() {
                                    return "application/json; charset=utf-8";
                                }

                                @Override
                                public byte[] getBody() throws AuthFailureError {
                                    try {
                                        return requestBody == null ? null : requestBody.getBytes("utf-8");
                                    } catch (UnsupportedEncodingException uee) {
                                        VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
                                        return null;
                                    }
                                }

                                @Override
                                protected Response<String> parseNetworkResponse(NetworkResponse response) {
                                    try {

    /**
  First you will have to convert the NetworkResponse into a jsonstring.
  Then that json string can be converted into the required java object
   using gson
   **/
                                        addEncodeing2Request(response);
                                        return 
 super.parseNetworkResponse(response);
                                    } catch (UnsupportedEncodingException e) {
                                        e.printStackTrace();
                                        return Response.error(new ParseError(e));
                                    }
                                }
                            };

                            requestQueue.add(stringRequest);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }


                    } else {
                        Toast.makeText(getApplicationContext(), "الرجاء قيول لائحة النظم", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "password does not match", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(getApplicationContext(), "password is not strong", Toast.LENGTH_SHORT).show();
            }
        }
    });



}

顺便说一下,解析网络方法中的return语句有编译错误 这是回复

                     {
                     "tblRegisteredUsers_UserPKID": 3034,
                         "tblRegisteredUsers_UserName": "hi21323",
                             "tblRegisteredUsers_Password": null,
"tblRegisteredUsers_FirstName": null,
"tblRegisteredUsers_SecondName": null,
"tblRegisteredUsers_LastName": null,
"tblRegisteredUsers_Country": null,
"tblRegisteredUsers_City": null,
"tblRegisteredUsers_Gender": null,
"tblRegisteredUsers_BirthDate": null,
"tblRegisteredUsers_Education": null,
"tblRegisteredUsers_Job": null,
"tblRegisteredUsers_HomePhone": null,
"tblRegisteredUsers_MobileNumber": null,
"tblRegisteredUsers_FaxNumber": null,
"tblRegisteredUsers_Email": null,
"tblRegisteredUsers_HowYouKnowUS": null,
"tblRegisteredUsers_Nationality": null,
"tblRegisteredUsers_Active": null,
"tblRegisteredUsers_PayType": null,
"tblRegisteredUsers_photo": null,
"tblRegisteredUsers_DraftInfo": null,
"tblRegisteredUsers_AccountStates": null,
"tblRegisteredUsers_registrationDate": null,
"tblRegisteredUsers_nickName": null,
"tblRegisteredUsers_Activeby_FKID": null,
"tblRegisteredUsers_ActivationDate": null,
"tblRegisteredUsers_Year": null,
"tblRegisteredUsers_ActivebyPayment": null,
"tblRegisteredUsers_intensified": null,
"tblRegisteredUsers_Shiping_Address": null,
"tblRegisteredUsers_intensified_Status": null,
"tblRegisteredUsers_ReactivationDateTime": null,
"tblRegisteredUsers_ActivebyPayment_Intensive": null,
"tblRegisteredUsers_ActivationDate_IntensiveChange": null,
"tblRegisteredUsers_Installment": null,
"tblRegisteredUsers_InstallmentActivationDate": null,
"tblRegisteredUsers_Installment_ActivePayment": null,
"tblRegisteredUsers_Hide": null,
"tblRegisteredUsers_Hide_User_FK_ID": null,
"tblRegisteredUsers_Hide_DateTime": null,
"tblRegisteredUsers_Renew_Datetime": null

}

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

如果你有一个特定的Json对象/结构,你可能想在某处实现MyStructureObject.class并将所有这些变量添加到它。

MyStructureObject{
String id;
   public String getIdField(){
      return id;
   }
... // add all other variables of your json structure
}

您可以使用com.google.code.gson(from maven gradle repository)之类的JSON库,并从JsonString中序列化(或反序列化)JsonObject。

MySturctureObject instance = new Gson().fromJson(yourJsonString,MyStructureObject.class);
String id = instance.getIdField();

我希望这有点帮助:) 我已经成功地在我自己的android java / libgdx应用程序中添加了gson库,但是也许你想要使用另一个库。 这只是一个建议。