package create. json;
import java. util. Iterator;
import org. json. JSONArray;
import org. json. JSONException;
import org. json. JSONObject; ;
class CreateJson1 {
public JSONArray create ( ) {
JSONObject json = new JSONObject ( ) ;
JSONObject json2 = new JSONObject ( ) ;
JSONObject json3 = new JSONObject ( ) ;
JSONArray jsonArray = new JSONArray ( ) ;
try {
json. put ( "name" , "张三" ) ;
json. put ( "age" , "11" ) ;
json. put ( "gader" , "male" ) ;
json2. put ( "name" , "李四" ) ;
json2. put ( "word" , "Hello World, I like Java" ) ;
jsonArray. put ( json) ;
jsonArray. put ( json2) ;
jsonArray. put ( json3) ;
System. out. println ( jsonArray) ;
} catch ( JSONException e) {
e. printStackTrace ( ) ;
}
return jsonArray;
}
}
class SpliteJson {
private JSONArray jsonArray;
public SpliteJson ( JSONArray jsonArray) {
this . jsonArray = jsonArray;
}
public void spliteJson ( ) {
try {
System. out. println ( "###Start###" ) ;
for ( int i = 0 ; i < jsonArray. length ( ) ; i++ ) {
JSONObject jsItem = jsonArray. getJSONObject ( i) ;
Iterator jsIterator = jsItem. keys ( ) ;
while ( jsIterator. hasNext ( ) ) {
String key = jsIterator. next ( ) . toString ( ) ;
String string = jsItem. get ( key) . toString ( ) ;
System. out. println ( key + ":" + string) ;
}
System. out. println ( "--------------------------" ) ;
}
System. out. println ( "###END###" ) ;
} catch ( JSONException e) {
e. printStackTrace ( ) ;
}
}
}
public class CreateJson {
public static void main ( String[ ] args) {
CreateJson1 cj1 = new CreateJson1 ( ) ;
JSONArray jsArray = cj1. create ( ) ;
SpliteJson sj = new SpliteJson ( jsArray) ;
sj. spliteJson ( ) ;
}
}
输出结果
[{"name":"张三","age":"11","gader":"male"},{"name":"李四","word":"Hello World, I like Java"},{}]
###Start###
name:张三
age:11
gader:male
--------------------------
name:李四
word:Hello World, I like Java
--------------------------
--------------------------
###END###