我在json字符串下面,想使用Java访问AlsoKnownAs列表。我可以使用getString作为名称,我也尝试过将getJSONArray用于alsoKnownAs,但是使用起来不太方便
{\"name\":\"moses\",\"alsoKnownAs\":[\"njai\", \"njenga\",\"musa\"]}
我可以按如下方式访问名称,但不能使用等效的getString方法来返回字符串列表或等效于getJSONArray的字符串列表
public static Person parsePersonJson(String json) {
JSONObject currentPerson;
String name;
try {
currentPerson = new JSONObject(json);
// so I can access the name like
name = currentPerson.getString("name");
//I was trying this to get the list but figure out I was using a list of json objects, so not how to get the list of stings
JSONArray arrayKnownAs = names.getJSONArray("alsoKnownAs");
List<String> alsoKnownAs= new ArrayList<>();
for (int i = 0, l = arrayKnownAs.length(); i < l; i++) {
String origin;
origin = arrayKnownAs[i];
alsoKnownAs.add(origin);
}
Person thisPerson = new Person(
//I instantiate person object here
);
return thisPerson;
} catch (org.json.JSONException e) {
// error
}
return null;
}
如果有人被卡在这里,原来我走在正确的轨道上,我可以使用getJSONArray访问List,但是当对每个成员进行迭代时,我都使用getString
public static Person parsePersonJson(String json) {
JSONObject currentPerson;
String name;
try {
currentPerson = new JSONObject(json);
// so I can access the name like
name = currentPerson.getString("name");
List<String> alsoKnownAs= new ArrayList<>();
//use getJSONArray to get the list
JSONArray arrayKnownAs = currentPerson.getJSONArray("alsoKnownAs");
for (int i = 0, l = arrayKnownAs.length(); i < l; i++) {
//This is where I was getting it wrong, i needed to use getString to access list items
alsoKnownAs.add(arrayKnownAs.getString(i));
}
Person thisPerson = new Person(
//I instantiate person object here
);
return thisPerson;
} catch (org.json.JSONException e) {
// error
}
return null;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句