Kan*_*dya -2 directory android json assets file
我有json文件我需要关于它的类文件
{
"CountryDetail":[
{
"C_country":"India",
"C_sunrise":1381107633,
"C_sunset":1381149604
},
"weatherDetail":
{
"w_id":711,
"w_main":"Smoke",
"w_description":"smoke",
}
,
"Tempdetail":
{
"t_temp":304.15,
"t_pressure":1009,
}
}
Run Code Online (Sandbox Code Playgroud)
Gop*_*ngh 21
试试这个你将得到该文件的JSONObject.(Json应该是有效的).你可以点击这里查看Json
JSONObject obj = new JSONObject(readJSONFromAsset());
public String readJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("yourFile.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
Run Code Online (Sandbox Code Playgroud)
对于Kotlin == >>
var obj = JSONObject(readJSONFromAsset())
fun readJSONFromAsset(): String? {
var json: String? = null
try {
val inputStream:InputStream = assets.open("yourFile.json")
json = inputStream.bufferedReader().use{it.readText()}
} catch (ex: Exception) {
ex.printStackTrace()
return null
}
return json
}
Run Code Online (Sandbox Code Playgroud)
如果您使用的是Kotlin Lnaguage(Android上较智能的Java版本),那么这应该可以回答您的问题。
该代码段是
val jsonfile: String = applicationContext.assets.open("ela.json").bufferedReader().use {it.readText()}
Run Code Online (Sandbox Code Playgroud)
该jsonfile是一个字符串。因此要将其转换/类型转换为JSONObject。您可以执行以下操作。
val jsonObject = JSONObject(jsonfile)
Run Code Online (Sandbox Code Playgroud)
这很简单。它为我工作。
答案的来源来自此链接。
| 归档时间: |
|
| 查看次数: |
28254 次 |
| 最近记录: |