【问题标题】:How to process the json to normal class object?如何将 json 处理为普通的类对象?
【发布时间】:2017-01-04 14:56:07
【问题描述】:

我正在使用带有参数的 JsonObjectRequest 进行发布请求(来自模型类)。看起来,

        SignUpRequest registrationRequest = new SignUpRequest();
        registrationRequest.setFirstName("fdffdfd");
        registrationRequest.setLastName("bbbbbb");
        registrationRequest.setEmail("Testing@kjkjgmail.com");
        registrationRequest.setDateOfBirth("1991-5-21");

        Gson gson = new Gson();
        String jsonString = gson.toJson(registrationRequest);

        JSONObject parameters = null;
        try {
            parameters = new JSONObject(jsonString);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.POST, uri, parameters,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.v("MainActivity", "In response :");
                        updateDisplayRegistration(response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d("MainActivity", "In failure :");
                        error.printStackTrace();
                    }
                });
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(postRequest);

SignUpRequest 类我有 setter 和 getter 方法。与响应方式类似,我也有 RegistrationInfo 类,它具有响应对象的设置器和获取器。

现在的问题是我如何处理响应以将其作为 RegistrationInfo 类对象。

protected void updateDisplayRegistration(JSONObject json){

        RegistrationInfo regInfo  = new RegistrationInfo(json.toString());

        Log.v("MainActivity","registered email is ::::: ---- ::: " + regInfo.getEmail());
}

但它返回 null。即使我直接在 json 对象上尝试过,它也没有返回任何值。

喜欢,json.getString("email");

我如何处理响应?

【问题讨论】:

    标签: java android json jsonobjectrequest


    【解决方案1】:

    有一个现有的库 Gson(有点特定于 com.google.Gson)可用于将 JsonObject 转换为 java bean。你可以这样做

    RegistrationInfo regInfo = new GSON(json.toString(),RegistrationInfo.class);

    Gson 库使用反射方法在内部将 JSON 字符串转换为 Java bean。

    【讨论】:

    • 你确定是 GSON.. 还是 Gson?因为对于 GSON,我找不到任何库,而且它给出了一个错误。
    猜你喜欢
    • 1970-01-01
    • 2021-12-11
    • 2021-06-07
    • 2020-05-27
    • 1970-01-01
    • 2016-09-14
    • 1970-01-01
    • 2014-10-29
    • 2018-05-15
    相关资源
    最近更新 更多