我有一个由JSONArray组成的JSON。如何从JSONArrays中获取关键字符串列表?
例如:
{
"mainKey": [
{
"keyValue1": [
{
"id": 9000,
"name": "John Doe"
}
]
},
{
"keyValue2": []
},
{
"keyValue3": []
},
{
"keyValue4": []
}
]
}
我想获得一个带有keyValue1,keyValue2等的ArrayList。我应该如何用Java做到这一点?
答案 0 :(得分:0)
试试这个:
JSONObject obj = new JSONObject(yourJsonString);
JSONArray array = obj.getJSONArray("mainKey");
for(int n = 0; n < array.length(); n++)
{
JSONObject keyObject = array.getJSONObject(n);
Iterator<?> keys = keyObject.keys();
while( keys.hasNext() ) {
String key = (String)keys.next();
if ( obj.get(key) instanceof JSONArray ) {
System.out.println(key);
}
}
}
答案 1 :(得分:0)
我在Android AsyncTask中执行此操作:
ArrayList<String> arrayList = new ArrayList<String>();
Spinner spinner;
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_fragment_class, container, false);
spinner = (Spinner) rootView.findViewByID(R.id.spinner);
LoadFromAPI task = new LoadFromAPI();
task.execute(url); // a valid url in a localhost
ArrayAdapter<String> adapter = new ArrayAdapter<String>(rootView.getContext(),
android.R.layout.simple_spinner_item, arrayList);
return rootView;
}
private class LoadFromAPI extends AsyncTask<String, Void, Void> {
protected void doInBackground (String... url) {
JSONObject obj = new JSONObject(yourJsonString);
JSONArray array = obj.getJSONArray("mainKey");
for(int n = 0; n < array.length(); n++)
{
JSONObject keyObject = array.getJSONObject(n);
Iterator<?> keys = keyObject.keys();
while( keys.hasNext() ) {
String key = (String)keys.next();
if ( obj.get(key) instanceof JSONArray ) {
arrayList.add(key);
}
}
}
}
答案 2 :(得分:0)
在Java 8中:
alert(colorsObj.color1[i]);