[英]JSON error org.json.JSONException: No value for item
After tweaking JSON response a bit the error has changed to W/System.err: org.json.JSONException: No value for retCode
. 调整JSON响应后,错误已更改为
W/System.err: org.json.JSONException: No value for retCode
。
The complete error:
完整的错误:
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err: org.json.JSONException: No value for retCode
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err: at org.json.JSONObject.get(JSONObject.java:389)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err: at org.json.JSONObject.getString(JSONObject.java:550)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err: at com.allianz.azemployee.ActivityRegister$2.serviceResult(ActivityRegister.java:194)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err: at com.allianz.azemployee.Net$1$1.run(Net.java:420)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err: at android.os.Handler.handleCallback(Handler.java:739)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err: at android.os.Looper.loop(Looper.java:148)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5417)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err: at java.lang.reflect.Method.invoke(Native Method)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
04-03 12:53:26.703 14366-14454/com.allianz.azemployee V/RenderScript: 0x9d789000 Launching thread(s), CPUs 4
This my ActivityRegister.java class: 这是我的ActivityRegister.java类:
public class ActivityRegister extends AppCompatActivity implements View.OnClickListener {
Button btnRequestPin, btnConfirm, btnRequestNewPin;
EditText editTextEmail;
EditText editTextPin;
private static final String FIRST_START_KEY = "first_start";
private static final boolean ALWAYS_SEND_FIRST_START_BROADCAST = false;
private String emailTemp, tokenTemp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
btnRequestPin = (Button)findViewById(R.id.btn_request_pin);
btnConfirm = (Button)findViewById(R.id.btn_confirm);
btnRequestNewPin = (Button)findViewById(R.id.btn_request_newpin);
editTextEmail = (EditText) findViewById(R.id.editText_mail);
editTextPin = (EditText) findViewById(R.id.editText_pin);
btnRequestPin.setOnClickListener(this);
btnConfirm.setOnClickListener(this);
btnRequestNewPin.setOnClickListener(this);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
}
@Override
public void onBackPressed() {
super.onBackPressed();
finish();
Intent intent = new Intent(this,ActivityLogin.class);
this.startActivity(intent);
}
@Override
public void onClick(View v) {
if(v == btnConfirm){
final String email = editTextEmail.getText().toString();
final String token = editTextPin.getText().toString();
if (email == null || email.length() == 0){
Toast.makeText(this,"Email required",Toast.LENGTH_SHORT).show();
return;
}
if (token == null || token.length() == 0){
Toast.makeText(this,"OTP required",Toast.LENGTH_SHORT).show();
return;
}
//Check if email is valid
if(!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()){
Toast.makeText(this,"Valid email required.",Toast.LENGTH_SHORT).show();
return;
}
String postBody = Net.getInstance().getJSONForRegister(email,token);
Net.getInstance().callServiceWithURLPart(this, Net.kURLPartEmpAuthentication, postBody, new Net.ICallServiceResult() {
@Override
public void serviceResult(String urlPart, boolean expected, String errorMsg) {
if(!expected){
if(errorMsg!=null){
Net.fastToast(ActivityRegister.this,"Unable to register. Try again.\n\n"+errorMsg);
}
else {
Net.fastToast(ActivityRegister.this,"Unable to register. Try again.");
}
}
else {
try {
JSONObject jsonObject = new JSONObject(errorMsg);
String retCode = jsonObject.getString("retCode");
String status = jsonObject.getString("status");
int retCodeInt = Integer.parseInt(retCode);
Net.fastToast(ActivityRegister.this,status);
if (retCodeInt==0) { //Registration success
//Store user-email and token
Net.getInstance().saveUserWithValues(ActivityRegister.this, email, token, "");
//Take user to login screen.
ActivityRegister.this.finish();
}
} catch (JSONException e) {
e.printStackTrace();
Net.fastToast(ActivityRegister.this,"Unable to get valid response for registration. Try again.");
}
}
}
});
}
if(v == btnRequestPin || v == btnRequestNewPin){
final String email = editTextEmail.getText().toString();
if (email == null || email.length() == 0){
Toast.makeText(this,"Email required",Toast.LENGTH_SHORT).show();
return;
}
//Check if email is valid
if(!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()){
Toast.makeText(this,"Valid email required.",Toast.LENGTH_SHORT).show();
return;
}
final Button button = (Button) v;
String postBody = Net.getInstance().getJSONForPinGeneration(email);
Net.getInstance().callServiceWithURLPart(this, Net.kURLPartEmpAuthentication, postBody, new Net.ICallServiceResult() {
@Override
public void serviceResult(String urlPart, boolean expected, String errorMsg) {
if(!expected){
Log.i("Aditi","errorMsg== " +errorMsg);
if(errorMsg!=null){
Net.fastToast(ActivityRegister.this,"Unable to generate pin. Try again.\n\n"+errorMsg);
}
else {
Net.fastToast(ActivityRegister.this,"Unable to generate pin. Try again.");
}
}
else {
try {
JSONObject jsonObject = new JSONObject(errorMsg);
String retCode = jsonObject.getString("retCode");
String status = jsonObject.getString("status");
Log.i("Aditi","retCode===" + retCode + " ,status== "+status);
Log.i("Aditi","errorMsg== " +errorMsg);
int retCodeInt = Integer.parseInt(retCode);
Net.fastToast(ActivityRegister.this,status);
if(retCodeInt == 0 && button == btnRequestNewPin){
ActivityRegister.this.finish(); //take user to login on success.
}
} catch (JSONException e) {
e.printStackTrace();
Net.fastToast(ActivityRegister.this,"Unable to get valid response for pin generation. Try again.");
}
}
}
});
}
}
}
This is the stringResponse I'm giving: 这是我给的stringResponse:
public void callServiceWithURLPart(final Activity activity, final String urlPart, final String postBody, final ICallServiceResult callServiceResult){
final ProgressDialog progress = new ProgressDialog(activity);
progress.setTitle("Processing..");
progress.setProgressStyle(android.R.attr.progressBarStyleSmall);
//progress.setMessage("Connecting...");
progress.show();
ConnectivityManager connMgr = (ConnectivityManager)
activity.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
Runnable r = new Runnable() {
@Override
public void run() {
OkHttpClient client = new OkHttpClient.Builder().connectTimeout(60, TimeUnit.SECONDS).build();
try{
String servicePath = kURLBase + urlPart;
Log.d("OkHttpClient","servicePath = "+servicePath);
Log.d("postBody",postBody);
Request request = new Request.Builder()
.url(servicePath)
.put(RequestBody.create(MEDIA_TYPE_JSON, postBody))
.build();
final Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
//final String stringResponse = response.body().string();
final String stringResponse = "{'serviceName': 'registerToken', 'emailID': '', 'token': ''}";
if(stringResponse!=null){
Log.d("ServiceResponseString",stringResponse);
}else {
Log.d("ServiceResponseString","null");
}
if(callServiceResult!=null){
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
progress.dismiss();
if(stringResponse!=null){
callServiceResult.serviceResult(urlPart,true,stringResponse);
}
else {
callServiceResult.serviceResult(urlPart,false,stringResponse);
}
}
});
}
} catch (Exception e){
Log.d("OkHttpClient exception",e.toString());
final Exception _e = e;
if(callServiceResult!=null){
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
progress.dismiss();
callServiceResult.serviceResult(urlPart,false,_e.toString());
}
});
}
}
}
};
Thread t = new Thread(r);
t.start();
} else {
progress.dismiss();
fastToast(activity,"Connect to internet and try again.");
}
}
My base URL is: public static final String kURLBase = "https://api-test.allianz.com/digithonempwebservice/rest";
我的基本URL是:
public static final String kURLBase = "https://api-test.allianz.com/digithonempwebservice/rest";
which is being provided when stringResponse is asked. 当请求stringResponse时提供。 Any help would be appreciated.
任何帮助,将不胜感激。
Try this: 尝试这个:
String retCode = jsonObject.optString("retCode");
The difference is that
optString
returns the empty string ("") if the key you specify doesn't exist.区别在于,如果您指定的键不存在,则
optString
返回空字符串(“”)。getString
on the other hand throws aJSONException
.另一方面,
getString
抛出JSONException
。 UsegetString
if it's an error for the data to be missing, or optString if you're not sure if it will be there.如果丢失数据是错误的,请使用
getString
如果不确定数据是否存在,请使用optString。
As the crash logs suggest, you are trying to access retCode
from the json but it not there. 正如崩溃日志所建议的那样,您正在尝试从json访问
retCode
,但并不在那里。
You should use optString
rather than getString
, if you are not sure about the fields. 如果不确定字段,则应使用
optString
而不是getString
。
JSON中没有retCode
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.