所以我有一个我已经解析过的Json文件,我想知道如何将Json文件中的信息传递给屏幕?继承人解析Json。
public String loadJSONFromAsset()
{
String json = null;
try
{
InputStream is = getAssets().open("JSON.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;
}
JSON:
{"answers":[
{
"answer": "1"
},
{
"answer": "2"
},
{
"answer": "3"
},
{
"answer": "4"
},
{
"answer": "5"
}
]}
如何将“4”变为变量?我希望我的问题很清楚,如果没有,请评论。我想要做的只是输出其中一个数字。
答案 0 :(得分:2)
使用此示例代码希望它能解决您的问题
private void parseJson(String json) {
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("answers");
for (int i = 0; i < jsonArray.length(); i++){
String answer = jsonArray.getJSONObject(i).getString("answer");
Log.i(TAG,"answer: "+answer);
}
} catch (Exception e) {
e.printStackTrace();
}
}
答案 1 :(得分:1)
解析JSON字符串。
JSONObject obj = new JSONObject(jsonString);
JSONArray answers = obj.getJSONArray("answers");
for (int i = 0; i < answers.length(); i++) {
// this will loop though all answers
JSONObject answerObj = answers.getJSONObject(i);
String answer = answerObj.getString("answer");
}
我建议搜索一些关于如何在java中解析JSON的例子,有很多例子和教程
答案 2 :(得分:0)
你需要一个Java Json库。
final JSONObject j = new JSONObject(parsed);
JSONArray answers = j.getJSONArray("answers");
System.out.println(answers.get(4));
答案 3 :(得分:0)
You should used this sample code
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("yourfilename.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;
}
读取Json文件,这总是使用try和catch块
try {
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONArray m_jArry = obj.getJSONArray("answers");
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
String answer = jo_inside.getString("answer");
}
} catch (JSONException e) {
e.printStackTrace();
}