import android.content.Context;
import com.commerce.img.entity.DataUrl;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class JsonUtil {
public DataUrl JsonToList(Context context) {
StringBuilder stringBuilder = new StringBuilder();
try {
BufferedReader bf = new BufferedReader(new InputStreamReader(
context.getAssets().open("img.json")));
String line;
while ((line = bf.readLine()) != null) {
stringBuilder.append(line);
}
Gson gson = new Gson();
DataUrl bean = gson.fromJson(stringBuilder.toString(), DataUrl.class);
return bean;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
DataUrl 为实体类
实体类的命名要和josn串键名一样
在Gson依赖('com.google.code.gson:gson:2.9.0')支持下可以通过@SerializedName("xxx")重命名
import android.content.Context
import com.google.gson.Gson
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
class JsonUtil {
fun <T> JsonToList(context: Context, fileName:String, template:Class<T>): T? {
val stringBuilder = StringBuilder()
try {
val bf = BufferedReader(
InputStreamReader(
context.assets.open("gif/$fileName.json")
)
)
var line: String?
while (bf.readLine().also { line = it } != null) {
stringBuilder.append(line)
}
val gson = Gson()
return gson.fromJson(stringBuilder.toString(),template)
} catch (e: IOException) {
e.printStackTrace()
}
return null
}
}