Kotlin Gsonを使用してローカルjsonデータを解析

18806 ワード

1.ローカルresフォルダの下にrawフォルダを新規作成し、jsonファイルを入れます.
1)javaロード方式:
public class StreamUtils {
	
	public static String get(Context context, int id) {
		InputStream stream = context.getResources().openRawResource(id);
		return read(stream);
	}
	
	public static String read(InputStream stream) {
		return read(stream, "utf-8");
	}
	
	public static String read(InputStream is, String encode) {
        if (is != null) {
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, encode));
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "
"
); } is.close(); return sb.toString(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return ""; } }
String data = StreamUtils.get(APP.getInstance(), R.raw.update);

2)Kotlinロード方式
class JsonReadUtils private constructor() {

    private object StreamUtilsInstance {
        val jsonReadUtils = JsonReadUtils()
    }

    companion object {
        fun getInstance(): JsonReadUtils {
            return StreamUtilsInstance.jsonReadUtils
        }
    }

    fun get(context: Context, id: Int): String {
        val stream = context.resources.openRawResource(id)
        return read(stream)
    }

    fun read(stream: InputStream): String {
        return read(stream, "utf-8")
    }

    fun read(inputStream: InputStream, encode: String): String {
        if (inputStream != null) {
            try {
                val reader = BufferedReader(InputStreamReader(inputStream, encode))
                var line = reader.readLine()
                var result = ""
                while (line != null) {
                    result += line
                    line = reader.readLine()
                }
                inputStream.close()
                return result
            } catch (e: UnsupportedEncodingException) {
                e.printStackTrace()
            } catch (e: IOException) {
                e.printStackTrace()
            }

        }
        return ""
    }
    
}
val data = JsonReadUtils.getInstance().get(context, R.raw.update)

2.Gson解析
1)Objectオブジェクトの解析:
val data = JsonReadUtils.getInstance().get(AppConfig.application!!, R.raw.update)
val bean: Bean = Gson().fromJson(data, Bean::class.java)

2)Array配列の解析
方法1:
val data = JsonReadUtils.getInstance().get(AppConfig.application!!, R.raw.update)
val type = object : TypeToken<List<Bean>>(){}.type
val listBe: List<Bean> = Gson().fromJson(data, type)

方式2:
inline fun <reified T> genericType() = object: TypeToken<T>() {}.type
val turnsType = genericType<List<Turns>>()

解析した配列にkey値がある場合
class Test(val deviceInfo: DeviceInfo) {

}

シーケンス番号
api
さぎょう
1
toJson(Object)
シーケンス化
2
fromJson(String, Class)
逆シーケンス化
3
JsonParser().parse(String)
解析フィールド
KotlinでのGson使用