運行結果:
--------------------------------------
Java代碼
//解析方法
public void parseJson(String jsonData) {
try {
JsonReader reader = new JsonReader(new StringReader(jsonData));
reader.beginArray();
while (reader.hasNext()) {
reader.beginObject();
while (reader.hasNext()) {
String tagName = reader.nextName();
if (tagName.equals("name")) {
System.out.print("name=" + reader.nextString() + " ");
} else if (tagName.equals("age")) {
System.out.println("age=" + reader.nextInt());
}
}
reader.endObject();
}
reader.endObject();
} catch (Exception e) {
e.printStackTrace();
}
}
===============================================
public class Main extends Activity {
/** Called when the activity is first created. */
private String jsonData = "[{\"name\":\"Jack\",\"age\":20},{\"name\":\"Tom\",\"age\":25}]";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
JsonUtils jsonUtils = new JsonUtils();
jsonUtils.parseJson(jsonData);
}
}
作者“Android開發”