本文使用谷歌的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方法即可打印,查看
json字符串文件转成bean的数组集合
banner_list.json文件内容为
[
{
"id": 1,
"title": "mvvm优化",
"desc": "MVVM框架下的大型项目优化、以及activity和viewmodel臃肿的优化",
"url": "https://blog.csdn.net/wy313622821/article/details/139878677",
"order": 2,
"type": 0,
"imagePath": "https://upload-images.jianshu.io/upload_images/23363983-2398ef0517e12e8b.jpg",
"isVisible": 1
},
{
"id": 2,
"title": "解决bug流程",
"desc": "解决bug流程",
"url": "https://blog.csdn.net/wy313622821/article/details/139853959",
"order": 1,
"type": 1,
"imagePath": "https://upload-images.jianshu.io/upload_images/23363983-798267084d9b9b31.jpg",
"isVisible": 1
},
{
"id": 3,
"title": "性能优化篇",
"desc": "android性能优化",
"url": "https://blog.csdn.net/wy313622821/article/details/106196402",
"order": 1,
"type": 1,
"imagePath": "https://upload-images.jianshu.io/upload_images/23363983-48c01bd2f6fc4a9c.jpg",
"isVisible": 1
}
]
转化的代码为:
object ParseFileUtils {
// suspend fun parseAssetsFile(assetManager: AssetManager, fileName: String): MutableList<VideoInfo> {
// return suspendCancellableCoroutine { continuation ->
// try {
// val inputStream = assetManager.open(fileName)
// //逐行读取,不用逐个字节读取
// val bufferedReader = BufferedReader(InputStreamReader(inputStream))
// var line: String?
// val stringBuilder = StringBuilder()
//
// do {
// line = bufferedReader.readLine()
// if (line != null) stringBuilder.append(line) else break
// } while (true)
//
// inputStream.close()
// bufferedReader.close()
//
// val list = stringBuilder.toString().toBean<MutableList<VideoInfo>>()// 这种方式只能解析固定的类型
// continuation.resumeWith(Result.success(list))
// } catch (e: Exception) {
// e.printStackTrace()
// continuation.resumeWithException(e)
// LogUtil.e(e)
// }
// }
// }
/**
* 解析assets目录下的文件(通用)
* @param assetManager
* @param fileName
* @return
*/
suspend inline fun <reified T> parseAssetsFile(assetManager: AssetManager, fileName: String): MutableList<T> {
return suspendCancellableCoroutine { continuation ->
try {
val inputStream = assetManager.open(fileName)
//逐行读取,不用逐个字节读取
val bufferedReader = BufferedReader(InputStreamReader(inputStream))
var line: String?
val stringBuilder = StringBuilder()
do {
line = bufferedReader.readLine()
if (line != null) stringBuilder.append(line) else break
} while (true)
inputStream.close()
bufferedReader.close()
// val list = stringBuilder.toString().toBean<MutableList<VideoInfo>>() // 这种方式只能解析固定的类型
val gson = Gson()
val type = object : TypeToken<MutableList<T>>() {}.type
val list = gson.fromJson<MutableList<T>>(stringBuilder.toString(), type)
continuation.resumeWith(Result.success(list))
} catch (e: Exception) {
e.printStackTrace()
continuation.resumeWithException(e)
LogUtil.e(e)
}
}
}
}
调用
ParseFileUtils.parseAssetsFile<Banner>(requireContext().assets, "banner_list.json")