Gson.toJson()的json与@ResponseBody的json区别!

Gson.toJson返回到前台的是json字符串,,需要js的$.parseJSON解析才能获取字段值!!!

@ResponseBody返回到前台的json是json对象,不需要解析,直接获取字段值!!!

package com.example.kucun2.entity; import android.annotation.SuppressLint; import androidx.annotation.Keep; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; @Keep // 防止Proguard混淆 public class Information<T> { private Integer status; private String text; private T data; // 使用泛型保证类型安全 private static final Gson gson = new Gson(); // Gson实例复用 // 构造方法 public Information(Integer status, String text, T data) { this.status = status; this.text = text; this.data = data; } // JSON反序列化构造方法 @SuppressLint("NewApi") public Information(Integer status, String text, String jsonData, Type dataType) { this.status = status; this.text = text; try { this.data = gson.fromJson(jsonData, dataType); } catch (JsonSyntaxException e) { this.data = null; // 处理解析失败 } } // 空构造方法 public Information() {} // 序列化为JSON public String toJson() { return gson.toJson(this); } // 静态创建方法 public static <T> Information<T> newSuccess(T data) { return new Information<>(200, "success", data); } public static Information<String> newSuccess(String text) { return new Information<>(200, "success", text); } public static <T> Information<T> newFail(int status, String text, T data) { return new Information<>(status, text, data); } // Getter/Setter public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getText() { return text; } public void setText(String text) { this.text = text; } public T getData() { return data; } public void setData(T data) { this.data = data; } } public static void post(String url, Information<?> data, ApiCallback callback) { // 实现POST请求逻辑 // Log.d("url", "loadAllData: "+url); Request request = new Request.Builder() .url(url) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(TAG, "Failed to load data", e); //if (callback != null) callback.onFailure(); } @Override public void onResponse(Call call, Response response) throws IOException { if (!response.isSuccessful()) { Log.e(TAG, "Unexpected response code: " + response.code()); //if (callback != null) callback.onFailure(); return; } String responseData = response.body().string(); //parseAndAssignData(responseData, context, callback); } });参数传入,返回类型为通信类
最新发布
06-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值