【问题标题】:How to send JSON response object from custom class to another activity android如何将 JSON 响应对象从自定义类发送到另一个活动 android
【发布时间】:2021-06-26 15:31:08
【问题描述】:

我在自定义类(非活动类)中获取 API 数据。现在我想将我的 JSON 响应对象解析为 Activity 类,但不能这样做。请教如何将响应对象从非活动类发送到活动类:

注意:我不想使用 Sharedpreference。

我的自定义类:

public class APIHelper {

    private static final String baseurl = "myUrl";
    private static final String loginAPI = "auth/login";

    public void getAPIResponse(Context context, View view, JSONObject parameters) {

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, baseurl + loginAPI, parameters, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

                //I want to send this response to another activity...

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                NetworkResponse response = error.networkResponse;
                if (error instanceof ServerError && response != null) {
                    try {

                        String res = new String(response.data, HttpHeaderParser.parseCharset(response.headers, "utf-8"));
                        JSONObject jsonObject = new JSONObject(res);
                        Utility.showSnackBar(view, jsonObject.getString("message"), "top", "error");

                    } catch (UnsupportedEncodingException | JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        RequestQueue queue = Volley.newRequestQueue(context);
        queue.add(jsonObjectRequest);

    }
}

【问题讨论】:

    标签: android json


    【解决方案1】:

    首先创建这个接口:

    public interface ApiService {
        onResponse(JSONObject json);
    }
    

    然后

    public class APIHelper {
    
        private static final String baseurl = "myUrl";
        private static final String loginAPI = "auth/login";
        private ApiService  apiService;
    
        public void setApiService(ApiService  apiService) {
           this.apiService = apiService;
        }
    
    
        public void getAPIResponse(Context context, View view, JSONObject parameters) {
    
            JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, baseurl + loginAPI, parameters, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                     apiService.onResponse(response);
                    //I want to send this response to another activity...
    
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
    
                    NetworkResponse response = error.networkResponse;
                    if (error instanceof ServerError && response != null) {
                        try {
    
                            String res = new String(response.data, HttpHeaderParser.parseCharset(response.headers, "utf-8"));
                            JSONObject jsonObject = new JSONObject(res);
                            Utility.showSnackBar(view, jsonObject.getString("message"), "top", "error");
    
                        } catch (UnsupportedEncodingException | JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
    
            RequestQueue queue = Volley.newRequestQueue(context);
            queue.add(jsonObjectRequest);
    
        }
    }
    

    在你的活动中:

    APIHelper api = new APIHelper();
    api.setApiService(new ApiService() {
                @Override
                public void onResponse(JSONObject res) {
                    //write your code
                }
    }
    api.getAPIResponse(context, view, params);
    
    

    此代码可能有语法错误,报告我修复它

    【讨论】:

    • 更改 ApiService api = new ApiService();到 APIHelper api = new APIHelper();休息正在工作。谢谢
    【解决方案2】:

    如果你使用 gson 会更容易。 只需按照以下步骤操作

    1. 将 gson 依赖添加到您的 gradle 中

      implementation 'com.google.code.gson:gson:2.8.7'
      
    2. 将您的 JSON 对象或 JSON 数组列表转换为这样的字符串。

      Gson gson = new Gson();
      String json = gson.toJson(arrayList);
      

    现在已转换为字符串。因此,您可以将其保存在 Utils 类或共享引用中。 要检索 JSON,请使用此

        // If you have JSON Object then put your class name which you are using to save data
    
        String savedJson = Utils.jsonStr;
        Type type = new TypeToken<YourModelClass>() {
        }.getType();
        
        YourModelClass model = gson.fromJson(json, type);
    
        // If you have JSON arraylist then
    
        String savedJson = Utils.jsonStr;
        Type type = new TypeToken<ArrayList<YourModelClass>>() {
        }.getType();
    
        ArrayList<YourModelClass> arrayList = gson.fromJson(json, type);
    

    【讨论】:

      猜你喜欢
      • 2012-08-04
      • 1970-01-01
      • 1970-01-01
      • 2014-12-05
      • 1970-01-01
      • 1970-01-01
      • 2014-09-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多