BUG描述:
明明引入了import com.alibaba.fastjson.JSON;但as顯示該引用未被使用。
JSONObject jsonObject= JSON.parseObject(data);的時候,as將parseObject標紅,表示無法識別進行處理。
BUG出現原因:
由於在該活動內涉及okhttp進行網絡通信,其中已經對JSON進行了定義,這與fastjson的JSON衝突,當涉及JSON的時候系統自動使用該定義導致無法引入fastjson的JSON包。
//okhttp已經定義了一個JSON對象
public static final MediaType JSON= MediaType.get("application/json; charset=utf-8");
。。。省略中間其他okhttp的內容
formBody = RequestBody.create(post,JSON);
解決辦法:
//將okhttp用到的JSON改名爲其他內容,解決衝突
public static final MediaType JSON1= MediaType.get("application/json; charset=utf-8");
。。。省略中間其他okhttp的內容
formBody = RequestBody.create(post,JSON1);
最後,放上我的MainActivity的代碼,供初學okhttp+fastjson的同學們參考。由於我也是第一次使用,可能有的地方寫的不夠好,如有不足請指正。
package com.example.testhrms; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.JSONObject; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.ConnectException; import java.net.SocketTimeoutException; import java.util.concurrent.TimeUnit; import okhttp3.Call; import okhttp3.Callback; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class LoginActivity extends AppCompatActivity { public static final MediaType JSON1= MediaType.get("application/json; charset=utf-8"); EditText et_userid; EditText et_userpwd; String username; String password; private JSONObject jsonfile; private String data;//接收服務器返回的數據 protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); //初始化資源控件 initView(); } //獲取資源控件id private void initView() { et_userid=findViewById(R.id.et_userid); et_userpwd=findViewById(R.id.et_userpwd); } //點擊登陸按鈕後執行 public void doLogin(View view) throws UnsupportedEncodingException { //首先獲取用戶輸入的賬號和密碼 username = et_userid.getText().toString().trim(); password = et_userpwd.getText().toString().trim(); Log.i("net_test", username+"/"+password); //判斷用戶輸入的賬號與密碼是否爲空 if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)){ Toast.makeText(this, "輸入不能爲空", Toast.LENGTH_SHORT).show(); return; } // else//兩個輸入都非空,準備執行okhttp { try { post_login(username,password); } catch (JSONException e) { e.printStackTrace(); } } } private void post_login(String username,String password) throws JSONException { //拼接要發送的json jsonfile=new JSONObject(); jsonfile.put("user_id",username); jsonfile.put("user_key",password); String post=jsonfile.toString(); //1,創建OKHttpClient對象 OkHttpClient okHttpClient=new OkHttpClient(); okHttpClient.newBuilder().connectTimeout(10, TimeUnit.SECONDS) .readTimeout(15, TimeUnit.SECONDS) .writeTimeout(150, TimeUnit.MILLISECONDS) .build(); RequestBody formBody; formBody = RequestBody.create(post,JSON1); //拼接url字符串 String s1=getString(R.string.server_url0); String s2="post_login.php";//post_login.php //String s3=getString(R.string.server_lasturl);//?Content-Type=application/json String url=s1+s2; Log.i("net_test", url); //2,創建一個Request Request request=new Request.Builder() .addHeader("Content-Type","application/json") .url(url) .post(formBody) .build(); Log.i("net_test","request創建成功"); //3,創建一個call對象 Call call = okHttpClient.newCall(request); //4,將請求添加到調度中 call.enqueue(new Callback() { @Override public void onFailure(@NotNull Call call, @NotNull IOException e) { Log.d("net_test", "onFailure: failure"); //用來看是否失敗 Log.d("net_test", e.toString()); if(e instanceof SocketTimeoutException) { Log.d("net_test", "超時異常"); } else if(e instanceof ConnectException) { Log.d("net_test", "連接異常"); } } @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { Log.d("net_test", "onResponse:response "); //用來看是否有響應 //利用fastjson處理json數據並準備保存到全局變量中 data=response.body().string(); Log.d("net_test", "成功返回結果:"+data); //成功返回結果:{"user_id":"15588399220","department_id":"1","user_name":"柳一菲","user_rank":"1"} //JSONObject jsonObject=JSON.parseObject(data); runOnUiThread(new Runnable() { @Override public void run() { //mytext.setText(data); if(data.equals("false1")) { Log.i("net_test", "密碼錯誤"); new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { Toast.makeText(LoginActivity.this, "密碼錯誤!", Toast.LENGTH_SHORT).show(); } }); } else if(data.equals("false2")) { Log.i("net_test", "賬號不存在"); new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { Toast.makeText(LoginActivity.this, "賬號不存在,請先聯繫管理員註冊!", Toast.LENGTH_SHORT).show(); } }); } else { Log.i("net_test", "登陸成功"); JSONObject jsonObject= JSON.parseObject(data); final String user_id=jsonObject.getString("user_id"); final String user_name=jsonObject.getString("user_name"); final String department_id=jsonObject.getString("department_id"); final String user_rank=jsonObject.getString("user_rank"); Log.i("net_test","json對象:" + user_id+"/"+user_name+"/"+department_id+"/"+user_rank); //處理傳回的用戶信息數據 myData.set_user_id(user_id); myData.set_department_id(department_id); myData.set_user_name(user_name); myData.set_user_rank(user_rank); Log.i("net_test","將賬戶信息相關的json存爲全局變量成功!:" + myData.get_user_id()+"/"+myData.get_department_id()+"/"+myData.get_user_name()+"/"+myData.get_user_rank()); //如果需要存儲的全局變量都被賦值成功則跳轉主頁面 if(!myData.get_user_id().equals("")&&!myData.get_user_name().equals("") &&!myData.get_user_rank().equals("")&&!myData.get_department_id().equals("")) { //Toast必須出現在主線程上。使用 new Handler(Looper.getMainLooper()) 來生成一個主線程 // handler 從任何後臺回線程,然後使用它發佈 toast 主線程的工作 new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { Toast.makeText(LoginActivity.this, "登陸成功!", Toast.LENGTH_SHORT).show(); //跳轉到主頁面 Intent intent = new Intent(LoginActivity.this, MainActivity.class); startActivity(intent); LoginActivity.this.finish(); } }); } } } }); } }); } //okhttp官網的post案例 // public static final MediaType JSON // = MediaType.get("application/json; charset=utf-8"); // // OkHttpClient client = new OkHttpClient(); // // String post(String url, String json) throws IOException { // RequestBody body = RequestBody.create(json, JSON); // Request request = new Request.Builder() // .url(url) // .post(body) // .build(); // try (Response response = client.newCall(request).execute()) { // return response.body().string(); // } // } //okhttp官網的get案例 // OkHttpClient client = new OkHttpClient(); // // String run(String url) throws IOException { // Request request = new Request.Builder() // .url(url) // .build(); // // try (Response response = client.newCall(request).execute()) { // return response.body().string(); // } // } }