Gson 布尔值bool与整形int相互转化

Gson 布尔值bool与整形int相互转化


import android.text.TextUtils;

import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;

/**
 * Description
 * author  youxuan  E-mail:xuanyouwu@163.com
 * date createTime:2017/4/8
 * version 1.0.0
 */
public class BooleanTypeAdapter extends TypeAdapter<Boolean> {
    @Override
    public void write(JsonWriter out, Boolean value) throws IOException {
        if (value == null) {
            out.nullValue();
        } else {
            out.value(value);
        }
    }

    @Override
    public Boolean read(JsonReader in) throws IOException {
        JsonToken peek = in.peek();
        switch (peek) {
            case BOOLEAN:
                return in.nextBoolean();
            case NULL:
                in.nextNull();
                return null;
            case NUMBER:
                return in.nextInt() != 0;
            case STRING:
                return toBoolean(in.nextString());
            default:
                throw new JsonParseException("Expected BOOLEAN or NUMBER but was " + peek);
        }
    }

    /**
     * true  TURE 都为true
     * "0" 为 false
     *
     * @param name
     * @return
     */
    public static boolean toBoolean(String name) {
        return (!TextUtils.isEmpty(name))
                &&
                (name.equalsIgnoreCase("true") || !name.equals("0"));
    }
}

模型:

import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.icourt.alpha.utils.BooleanTypeAdapter;

/**
 * @author xuanyouwu
 * @email xuanyouwu@163.com
 * @time 2016-06-01 16:59
 * <p>
 * 不要轻易修改
 * 不要轻易修改
 */

public class ResEntity<T> {
    private static final String FIELD_SUCCEED = "succeed";
    private static final String FIELD_MESSAGE = "message";
    private static final String FIELD_RESULT = "result";

    @SerializedName(value = FIELD_MESSAGE, alternate = {"resultMess"})
    public String message;

    @JsonAdapter(BooleanTypeAdapter.class)
    @SerializedName(value = FIELD_SUCCEED, alternate = {"resultCode"})
    public boolean succeed;

    @SerializedName(value = FIELD_RESULT, alternate = {"data"})
    public T result;

    @Override
    public String toString() {
        return "ResEntity{" +
                "message='" + message + '\'' +
                ", succeed=" + succeed +
                ", result=" + result +
                '}';
    }
}

用法 将整形转化为bool 在这个字段上面加上@JsonAdapter(BooleanTypeAdapter.class)

验证:

private void test() {
        String json1 = "{\n" +
                "  \"detail\": \"返回错误\",\n" +
                "  \"message\": \"错误1\",\n" +
                "  \"result\": {},\n" +
                "  \"succeed\": true\n" +
                "}";
        try {
            NetRes netRes = JsonUtils.Gson2Bean(json1, NetRes.class);
            LogUtils.d("---------->netRes1:" + netRes);
        } catch (JsonParseException e) {
            LogUtils.d("-------->解析异常1:" + e);
        }


        String json2 = "{\n" +
                "  \"detail\": \"返回错误\",\n" +
                "  \"message\": \"错误2\",\n" +
                "  \"result\": {},\n" +
                "  \"succeed\": \"1\"\n" +
                "}";
        try {
            NetRes netRes = JsonUtils.Gson2Bean(json2, NetRes.class);
            LogUtils.d("---------->netRes2:" + netRes);
        } catch (JsonParseException e) {
            LogUtils.d("-------->解析异常2:" + e);
        }
        String json3 = "{\n" +
                "  \"detail\": \"返回错误\",\n" +
                "  \"message\": \"错误3\",\n" +
                "  \"result\": {},\n" +
                "  \"succeed\": \"0\"\n" +
                "}";

        try {
            NetRes netRes = JsonUtils.Gson2Bean(json3, NetRes.class);
            LogUtils.d("---------->netRes3:" + netRes);
        } catch (JsonParseException e) {
            LogUtils.d("-------->解析异常3:" + e);
        }

        String json4 = "{\n" +
                "  \"detail\": \"返回错误\",\n" +
                "  \"resultMess\": \"错误4\",\n" +
                "  \"result\": {},\n" +
                "  \"succeed\": \"1\"\n" +
                "}";
        try {
            NetRes netRes = JsonUtils.Gson2Bean(json4, NetRes.class);
            LogUtils.d("---------->netRes4:" + netRes);
        } catch (JsonParseException e) {
            LogUtils.d("-------->解析异常4:" + e);
        }

        String json5 = "{\n" +
                "  \"detail\": \"返回错误\",\n" +
                "  \"resultMess\": \"错误5\",\n" +
                "  \"result\": {},\n" +
                "  \"resultCode\": \"1\"\n" +
                "}";
        try {
            NetRes netRes = JsonUtils.Gson2Bean(json5, NetRes.class);
            LogUtils.d("---------->netRes5:" + netRes);
        } catch (JsonParseException e) {
            LogUtils.d("-------->解析异常5:" + e);
        }

        String json6 = "{\n" +
                "  \"detail\": \"返回错误\",\n" +
                "  \"resultMess\": \"错误6\",\n" +
                "  \"result\": {},\n" +
                "  \"resultCode\": \"0\"\n" +
                "}";
        try {
            NetRes netRes = JsonUtils.Gson2Bean(json6, NetRes.class);
            LogUtils.d("---------->netRes6:" + netRes);
        } catch (JsonParseException e) {
            LogUtils.d("-------->解析异常6:" + e);
        }

        String json7 = "{\n" +
                "  \"detail\": \"返回错误\",\n" +
                "  \"resultMess\": \"错误7\",\n" +
                "  \"result\": {},\n" +
                "  \"resultCode\": true\n" +
                "}";
        try {
            NetRes netRes = JsonUtils.Gson2Bean(json7, NetRes.class);
            LogUtils.d("---------->netRes7:" + netRes);
        } catch (JsonParseException e) {
            LogUtils.d("-------->解析异常7:" + e);
        }

        String json8 = "{\n" +
                "  \"detail\": \"返回错误\",\n" +
                "  \"resultMess\": \"错误8\",\n" +
                "  \"result\": {},\n" +
                "  \"resultCode\": false\n" +
                "}";
        try {
            NetRes netRes = JsonUtils.Gson2Bean(json8, NetRes.class);
            LogUtils.d("---------->netRes8:" + netRes);
        } catch (JsonParseException e) {
            LogUtils.d("-------->解析异常8:" + e);
        }

        String json9 = "{\n" +
                "  \"detail\": \"返回错误\",\n" +
                "  \"resultMess\": \"错误9\",\n" +
                "  \"result\": {},\n" +
                "  \"resultCode\": 0\n" +
                "}";
        try {
            NetRes netRes = JsonUtils.Gson2Bean(json9, NetRes.class);
            LogUtils.d("---------->netRes9:" + netRes);
        } catch (JsonParseException e) {
            LogUtils.d("-------->解析异常9:" + e);
        }

        String json10 = "{\n" +
                "  \"detail\": \"返回错误\",\n" +
                "  \"resultMess\": \"错误10\",\n" +
                "  \"result\": {},\n" +
                "  \"resultCode\": 1\n" +
                "}";
        try {
            NetRes netRes = JsonUtils.Gson2Bean(json10, NetRes.class);
            LogUtils.d("---------->netRes10:" + netRes);
        } catch (JsonParseException e) {
            LogUtils.d("-------->解析异常10:" + e);
        }

        String json11 = "{\n" +
                "  \"detail\": \"返回错误\",\n" +
                "  \"resultMess\": \"错误11\",\n" +
                "  \"result\": {},\n" +
                "  \"resultCode\": \"\"\n" +
                "}";
        try {
            NetRes netRes = JsonUtils.Gson2Bean(json11, NetRes.class);
            LogUtils.d("---------->netRes11:" + netRes);
        } catch (JsonParseException e) {
            LogUtils.d("-------->解析异常11:" + e);
        }

        String json12 = "{\n" +
                "  \"detail\": \"返回错误\",\n" +
                "  \"resultMess\": \"错误12\",\n" +
                "  \"result\": {},\n" +
                "  \"resultCode\": null\n" +
                "}";
        try {
            NetRes netRes = JsonUtils.Gson2Bean(json12, NetRes.class);
            LogUtils.d("---------->netRes12:" + netRes);
        } catch (JsonParseException e) {
            LogUtils.d("-------->解析异常12:" + e);
        }

        String json13 = "{\n" +
                "  \"detail\": \"返回错误\",\n" +
                "  \"resultMess\": \"错误12\",\n" +
                "  \"result\": {},\n" +
                "  \"resultCode\":\n" +
                "}";
        try {
            NetRes netRes = JsonUtils.Gson2Bean(json13, NetRes.class);
            LogUtils.d("---------->netRes13:" + netRes);
        } catch (JsonParseException e) {
            LogUtils.d("-------->解析异常13:" + e);
        }
    }


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
可以通过以下步骤实现 ResultSet 与 JSON 相互转化: 1. 将 ResultSet 转化为 List<Map<String, Object>> 对象。 2. 使用 Gson 将 List<Map<String, Object>> 对象转化为 JSON 格式的字符串。 3. 使用 Gson 将 JSON 格式的字符串转化为 List<Map<String, Object>> 对象。 4. 将 List<Map<String, Object>> 对象转化为 ResultSet 对象。 以下是 Java 代码示例: ```java import com.google.gson.Gson; import java.sql.*; import java.util.*; public class ResultSetToJson { public static void main(String[] args) throws SQLException { // 获取数据库连接 Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=false", "root", "password"); // 执行 SQL 查询语句 Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM users"); // 将 ResultSet 转化为 List<Map<String, Object>> 对象 List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>(); ResultSetMetaData metaData = rs.getMetaData(); int columnCount = metaData.getColumnCount(); while (rs.next()) { Map<String, Object> map = new HashMap<String, Object>(); for (int i = 1; i <= columnCount; i++) { String columnName = metaData.getColumnLabel(i); Object value = rs.getObject(columnName); map.put(columnName, value); } resultList.add(map); } // 使用 Gson 将 List<Map<String, Object>> 对象转化为 JSON 格式的字符串 Gson gson = new Gson(); String json = gson.toJson(resultList); System.out.println(json); // 使用 Gson 将 JSON 格式的字符串转化为 List<Map<String, Object>> 对象 List<Map<String, Object>> resultList2 = gson.fromJson(json, List.class); // 将 List<Map<String, Object>> 对象转化为 ResultSet 对象 ResultSetMetaData metaData2 = rs.getMetaData(); ResultSet rs2 = new ResultSetImpl(resultList2, metaData2); while (rs2.next()) { System.out.println(rs2.getInt("id") + " " + rs2.getString("name")); } // 关闭 ResultSet、Statement 和 Connection 对象 rs.close(); stmt.close(); conn.close(); } } class ResultSetImpl implements ResultSet { private List<Map<String, Object>> resultList; private ResultSetMetaData metaData; private int rowIndex = -1; public ResultSetImpl(List<Map<String, Object>> resultList, ResultSetMetaData metaData) { this.resultList = resultList; this.metaData = metaData; } @Override public boolean next() throws SQLException { rowIndex++; return rowIndex < resultList.size(); } @Override public String getString(String columnLabel) throws SQLException { Object value = resultList.get(rowIndex).get(columnLabel); return value == null ? null : value.toString(); } // 实现 ResultSet 接口中的其他方法 } ``` 需要注意的是,由于 ResultSet 接口中的方法较多,以上代码仅实现了部分方法,具体实现可根据需求进行扩展。另外,由于 ResultSet 接口是只读的,因此在实现 ResultSet 接口时不能包含更新、插入或删除等方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

亚洲小炫风

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值