gpt4 book ai didi

java - JSON 错误 org.json.JSONException : No value for item

转载 作者:行者123 更新时间:2023-12-01 20:52:02 24 4
gpt4 key购买 nike

稍微调整 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

这是我的 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.");
}
}

}
});
}
}
}

这是我给出的 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.");
}
}

我的基本 URL 是:public static final String kURLBase = "https://api-test.allianz.com/digithonempwebservice/rest";,当询问 stringResponse 时会提供该 URL。任何帮助将不胜感激。

最佳答案

试试这个:

String retCode = jsonObject.optString("retCode");

The difference is that optString returns the empty string ("") if the key you specify doesn't exist. getString on the other hand throws a JSONException. Use getString if it's an error for the data to be missing, or optString if you're not sure if it will be there.

关于java - JSON 错误 org.json.JSONException : No value for item,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43178939/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com