gpt4 book ai didi

android - 无法保存来自 json 数组的数据

转载 作者:行者123 更新时间:2023-11-29 19:08:30 37 4
gpt4 key购买 nike

我正在尝试从 json 数组文件中提取一些数据,我按照以下步骤操作 Reading a Json Array in android

json 数组的 fragment :

[
{
"JobNo": 1,
"JobTime": 30,
"JobDate": "20170911",
"WorkerTime": 27,
"JobTimeError": -3
},
{
"JobNo": 2,
"JobTime": 22,
"JobDate": "20170911",
"WorkerTime": 21,
"JobTimeError": -1
},

我想做的是,提取数据并将它们存储到自己的数组中,JobNo 到 JobNo 数组等。下面的代码是我的尝试,但它不存储值(在 toast 时崩溃因为它说数组中没有数据)。谢谢

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner staticSpinner = (Spinner) findViewById(R.id.static_spinner);
ArrayList<Integer> JobNo = new ArrayList<>();
ArrayList<Integer> JobTime= new ArrayList<>();
ArrayList<String> JobDate= new ArrayList<>();
ArrayList<Integer> WorkerTime= new ArrayList<>();
ArrayList<Integer> JobTimeError = new ArrayList<>();

try {
JSONObject json = new JSONObject(loadJSONFromAsset());
JSONArray jArray = json.getJSONArray("Data");

for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
int JobN = json_data.getInt("JobNo");
int JobT = json_data.getInt("JobTime");
String JobD = json_data.getString("JobDate");
int WorkT = json_data.getInt("WorkerTime");
int JobTE = json_data.getInt("JobTimeError");
JobNo.add(JobN);
JobTime.add(JobT);
JobDate.add(JobD);
WorkerTime.add(WorkT);
JobTimeError.add(JobTE);

}
}
catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(this,
JobDate.get(1),
Toast.LENGTH_LONG).show();
}

public String loadJSONFromAsset() {
String json = null;
try {

InputStream is = getAssets().open("convertcsv.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 字符串不是 JSON 对象,它是一个 JSON 数组,所以使用:

JSONArray jArray = new JSONArray (loadJSONFromAsset());

关于android - 无法保存来自 json 数组的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46259998/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com