这是我的JSON文件:
IntVar
我原来的方法是在for循环中这样做:
from tkinter import *
def button_placement(canvas):
xpos, ypos = 150, 25
for button_number in range(1, 11):
button = Button(canvas, width='5', height='2', text=button_number,
anchor=CENTER, command=
lambda id=button_number: button_action(id))
window = canvas.create_window(xpos, ypos, window=button)
ypos += 50
def button_action(button_identifier):
print('Button {} pressed'.format(button_identifier))
root = Tk()
canvas = Canvas(root, height=500)
button_placement(canvas)
canvas.pack()
canvas.mainloop()
但如果我有100个或更多呢?
"charts": {
"system_voltage": {
"enabled": true,
"title": "System Voltage",
"xaxis_label": null,
"yaxis_label": null,
"y_min": 0,
"y_max": 18,
"status": false
},
"temperature1": {
"enabled": true,
"title": "Box1 Temp",
"xaxis_label": null,
"yaxis_label": null,
"y_min": -30,
"y_max": 50,
"status": false
},
"temperature2": {
"enabled": true,
"title": "Amb Temp",
"xaxis_label": null,
"yaxis_label": null,
"y_min": -30,
"y_max": 50,
"status": true
}, ...
内的每个对象都是唯一的。如何循环访问JSONObject并将每个对象分配给JSON数组而不手动执行?
JSONObject objSysVoltage = chartss.getJSONObject("system_voltage");
答案 0 :(得分:3)
使用keys()方法获取所有密钥并获取JSONObject
表单密钥。
Iterator<?> keys = chartss.keys();
while( keys.hasNext() ) {
String key = (String)keys.next();
if ( chartss.get(key) instanceof JSONObject ) {
JSONObject josnObject = chartss.getJSONObject(key);
}
}
答案 1 :(得分:0)
使用JsonObjectRequest和JSONArray
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override public void onResponse(JSONObject chartss) {
try {
JSONArray JA = chartss.getJSONArray("charts");
String productArray[]= new String[JA.length()];
for (int i=0; i<JA.length();i++){
productArray[i]=JA.getString(i);
Log.d("Result",JA.getString(i));
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_dropdown_item_1line, productArray);
t2.setAdapter(dataAdapter);
String T1 = t2.getSelectedItem().toString();
t1.setText(T1);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
rq.add(request);}
t2是一个微调器,t1是textview
t2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
t1.setText(productArray[position]);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});