我正在尝试在Android中进行JSON解析。我可以解析值,但是有问题。例如,我使用此JSON。
我做了这个功能:
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray person = jsonObj.getJSONArray("person ");
for (int i = 0; i < person .length(); i++) {
JSONObject c = person .getJSONObject(i);
String id = c.getString("id");
String name= c.getString("name");
String age= c.getString("age");
HashMap<String, String> persons = new HashMap<>();
persons .put("id", id);
persons .put("name", name);
persons .put("age", age);
personList.add(persons);
并用于显示我的屏幕:
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
ListAdapter adapter = new SimpleAdapter(
Mainlayout.this, personList,
R.layout.person_list, new String[]{"name", "age"},
new int[]{
R.id.name,R.id.age});
lv.setAdapter(adapter);
}
我可以在ListView中看到所有数据,但是我想对年龄进行汇总。我在StackOverflow上找到了this,但我听不懂。我如何总结它们?
答案 0 :(得分:0)
你必须喜欢
23:28:30.137 10.7695982757
23:28:30.161 10.4071263594
23:28:30.187 9.23969855461
23:28:30.212 9.21066485657
23:28:30.238 9.25117645762
23:28:30.262 9.59227680741
23:28:30.287 9.9773536301
23:28:30.312 10.0128275058
23:28:30.337 9.73353441664
23:28:30.361 9.75064993988
23:28:30.387 9.717339267
23:28:30.412 9.72736788911
23:28:30.440 9.62451269364
int totalAge = 0;
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray person = jsonObj.getJSONArray("person ");
for (int i = 0; i < person .length(); i++) {
JSONObject c = person .getJSONObject(i);
String id = c.getString("id");
String name= c.getString("name");
String age= c.getString("age");
totalAge = totalAge + Integer.ParseInt(age);
HashMap<String, String> persons = new HashMap<>();
persons .put("id", id);
persons .put("name", name);
persons .put("age", age);
personList.add(persons);
会给您年龄。
答案 1 :(得分:0)
由于U可以解析JSON值,因此U可以使用以下代码:)
只需全局声明一个变量并将其用于求和
private int sumOfAge = 0;
private int ageValue;
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray person = jsonObj.getJSONArray("person ");
for (int i = 0; i < person .length(); i++) {
JSONObject c = person .getJSONObject(i);
String id = c.getString("id");
String name= c.getString("name");
String age= c.getString("age");
ageValue = Integer.parseInt(age);
sumOfAge+=ageValue;
HashMap<String, String> persons = new HashMap<>();
persons .put("id", id);
persons .put("name", name);
persons .put("age", age);
personList.add(persons);