SoFunction
Updated on 2025-03-02

Android uses OKHTTP to parse JSON data instance code

For code reuse, we first encapsulate a class. This class is HttpUtil


package ;
 
import ;
import ;
 
public class HttpUtil {
 
  public static void sendOkHttpRequest(final String address, final  callback) {
    OkHttpClient client = new OkHttpClient();
    Request request = new ()
        .url(address)
        .build();
    (request).enqueue(callback);
  }
 
}

Then the old rule is to write an entity class that contains the get/set method, and for the convenience of this, it is named


package ;
 
public class App {
 
  private String other;
 
  private String u_Name;
 
  private String u_id;
 
  private String u_passWord;
 
  private String u_token;
 
  private String u_userName;
 
  public String getOther() {
    return other;
  }
 
  public void setOther(String other) {
     = other;
  }
 
  public String getU_Name() {
    return u_Name;
  }
 
  public void setU_Name(String u_Name) {
    this.u_Name = u_Name;
  }
 
  public String getU_id() {
    return u_id;
  }
 
  public void setU_id(String u_id) {
    this.u_id = u_id;
  }
 
  public String getU_passWord() {
    return u_passWord;
  }
 
  public void setU_passWord(String u_passWord) {
    this.u_passWord = u_passWord;
  }
 
  public String getU_token() {
    return u_token;
  }
 
  public void setU_token(String u_token) {
    this.u_token = u_token;
  }
 
  public String getU_userName() {
    return u_userName;
  }
 
  public void setU_userName(String u_userName) {
    thisu_userName = u_userName;
  }
}

Last written

At the same time, for the purpose of code optimization and for the operation of UI threads, you can write this way.


package ;

import ;
import .;
import ;
import ;
import ;
import ;
 
import ;
import ;
 
import ;
import ;
 
import ;
import ;
 
public class MainActivity extends AppCompatActivity implements ViewOnClickListener{
 
  String url="Resolved Address";
  TextView responseText;
 
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    (savedInstanceState);
    setContentView(.activity_main);
    Button sendRequest = (Button) findViewById(.send_request);
    responseText = (TextView) findViewById(.response_text);
    (this);
  }
 
  @Override
  public void onClick(View v) {
    //After clicking here, clicking, call the network request sendRequestWithOkHttp method after clicking    if (() == .send_request) {
      sendRequestWithOkHttp();
    }
  }
 
  private void sendRequestWithOkHttp() {
    new Thread(new Runnable() {
      @Override
      public void run() {
        //Execute the Http request in the child thread and call back the final request result to        (url,new (){
          @Override
          public void onResponse(Call call, Response response) throws IOException {
            //Get the specific content returned by the server            String responseData=responsebody()string();
            parseJSONWithGSON(responseData);
            //Show the UI interface and call the showResponse method            showResponse(());
          }
          @Override
          public void onFailure(Call call,IOException e){
            //Exception case handling is performed here          }
        });
      }
    }).start();
  }
 
  private void parseJSONWithGSON(String jsonData) {
    //Json obtained by using lightweight Gson parsing    Gson gson = new Gson();
    List<App> appList = (jsonData, new TypeToken<List<App>>() {}.getType());
    for (App app : appList) {
      //Console output results for easy viewing      ("MainActivity", "other" + ());
      ("MainActivity", "u_Name" + app.getU_Name());
      ("MainActivity", "u_id" + app.getU_id());
      ("MainActivity", "u_passWord" + app.getU_passWord());
      ("MainActivity", "u_token" + app.getU_token());
    }
  }
  private void showResponse(final String response) {
    //Update the UI in the child thread    runOnUiThread(new Runnable() {
      @Override
      public void run() {
        // Perform UI operations here to display the results on the interface        (response);
      }
    });
  }
}

Does it feel comfortable to drive like this? This writing method avoids the blockage of Android program network requests to the greatest extent possible to affect the main thread. Of course, you can directly pull this code and copy it down.

In Java 1.8, Lambda expressions seem to be added, so what can I do with expressions?

The easiest thing is to simplify writing operations. For example, the method of starting threads under showResponse can be written like this:

// Here we use the Lambda expression to start the thread using the new feature of Java8  private void showResponse2(final String response) {
    //Update the UI in the child thread    runOnUiThread(() -> {
        // Perform UI operations here to display the results on the interface        responseTextsetText(response);
    });
  }

This makes it much simpler. In addition, click events are also very suitable for Lambda expressions. Using expressions can simplify the click events of a button in this way:

Button button = (Button)findViewById();
(v->{
  // Handle click events});

Or write it like this:

Button button = (Button)findViewById(.bytton1);
((v)->{
  // Handle click events});

This is the end of this point. I have also moved from Java to Android. The code can only be like this, and there will definitely be better in the future.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.