java——json工具类(json字符串转实体bean)、bean和字符串之间的转换、打印bean

本文使用谷歌的Gson来解析,导入包:
implementation 'com.google.code.gson:gson:2.2.+'

首先在Android studio上安装插件 GsonFormat-Plus,安装好了之后新建一个bean类,然后光标停在类名中按下alt+s(注意:需要新建java文件才能使用,kotlin文件中没反应):

 然后把想要转换的json字符串放进去,然后点设置:

 一直确认就可以生成bean的实体了。

jsonUtil的工具类:

package com.example.test2;

import com.google.gson.Gson;
import com.google.gson.JsonNull;
import com.google.gson.JsonSyntaxException;
import org.json.JSONObject;
import java.lang.reflect.Type;

public class JsonUtil {
    private JsonUtil() {
    }
    //饿汉单例
    private static final JsonUtil instance = new JsonUtil();
    public static JsonUtil getInstance(){
        return instance;
    }

    private static Gson gson = new Gson();


    /**
     * @param src :将要被转化的对象
     * @return :转化后的JSON串
     * @MethodName : toJson
     * @Description : 将对象转为JSON串,此方法能够满足大部分需求
     */
    public static String toJson(Object src) {
        if (null == src) {
            return gson.toJson(JsonNull.INSTANCE);
        }
        try {
            return gson.toJson(src);
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param json
     * @param classOfT
     * @return
     * @MethodName : fromJson
     * @Description : 用来将JSON串转为对象,但此方法不可用来转带泛型的集合
     */
    public static <T> Object fromJson(String json, Class<T> classOfT) {
        try {
            return gson.fromJson(json, (Type) classOfT);
        } catch (JsonSyntaxException e) {
            System.out.println(e.toString() + "------------------------------");
            e.printStackTrace();
        }
        return null;
    }


    /**
     * @param json
     * @param typeOfT
     * @return
     * @MethodName : fromJson
     * @Description : 用来将JSON串转为对象,此方法可用来转带泛型的集合,如:Type为 new
     * TypeToken<GiveLikeList<T>>(){}.getType()
     * ,其它类也可以用此方法调用,就是将List<T>替换为你想要转成的类
     */
    public static Object fromJson(String json, Type typeOfT) {
        try {
            return gson.fromJson(json, typeOfT);
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取json中的某个值
     *
     * @param json
     * @param key
     * @return
     */
    public static String getValue(String json, String key) {
        try {
            JSONObject object = new JSONObject(json);
            return object.getString(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取json中的list值
     *
     * @param json
     * @return
     */
    public static String getListValue(String json) {
        try {
            JSONObject object = new JSONObject(json);
            return object.getString("list");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Double getDoubleValue(String json, String key) {
        try {
            JSONObject object = new JSONObject(json);
            return object.getDouble(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static int getIntValue(String json, String key) {
        try {
            JSONObject object = new JSONObject(json);
            return object.getInt(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
    /**
     * json字符串 转 list
 """
    [
        {"id": 1, "name": "Bean1"},
        {"id": 2, "name": "Bean2"}
    ]
    """
     */
//    inline fun <reified T> jsonStringToList(jsonString: String): List<T> {
//        try {
//            val gson = Gson()
//            val type = object : TypeToken<List<T>>() {}.type
//            return gson.fromJson(jsonString.trimIndent(), type)
//        } catch (e: JsonSyntaxException) {
//            e.printStackTrace()
//        }
//        return emptyList()
//    }

}

使用:

 String str="{\"name\":\"BeJson\",\"url\":\"http://www.bejson.com\",\"links\":[{\"name\":\"Google\",\"url\":\"http://www.google.com\"},{\"name\":\"Baidu\",\"url\":\"http://www.baidu.com\"},{\"name\":\"SoSo\",\"url\":\"http://www.SoSo.com\"}]}";

        TestBean oo= (TestBean) JsonUtil.getInstance().fromJson(str,TestBean.class);
        Log.e("wangyao",oo.getName());
        Log.e("wangyao",oo.getLinks().get(1).getUrl());

kotlin bean和字符串之间的转换

    /**
     * json字符串 转 bean
     */
    open fun <T> strToBean(json: String?, classOfT: Class<T>?): T? {
        try {
            val gson = Gson()
            return gson.fromJson(json, classOfT)
        } catch (e: JsonSyntaxException) {
            println("$e------------------------------")
            e.printStackTrace()
        }
        return null
    }

    /**
     * bean 转 json字符串
     */
    fun beanToStr(src: Any?): String? {
        if (null == src) {
            return Gson().toJson(JsonNull.INSTANCE)
        }
        try {
            return Gson().toJson(src)
        } catch (e: JsonSyntaxException) {
            e.printStackTrace()
        }
        return null
    }

使用:

val user = User("张三", "18")
        val str = beanToStr(user)
        Log.e("TAG", "===1" + str)
        val aaBean = strToBean(str, User::class.java)
        Log.e("TAG", "===2" + aaBean?.studentName)




data class User(val studentName: String, val studentAge: String)

输出:

打印bean

调用beanToStr方法即可打印,查看

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

wy313622821

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

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

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

打赏作者

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

抵扣说明:

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

余额充值