您的评价: |
|
收藏该经验
|
这两个是官网的API
里面有这两个类的所有方法,是不可多得的好材料哦~
配合上面的API,大家再看下这段代码,就会大有收获了~
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.util.*;
/** *
* @author derek
*/ public class JavaTest {
public static void main(String[] args){
JSONObject obj= new JSONObject();
obj.put( "derek" , "23" );
obj.put( "dad" , "49" );
obj.put( "mom" , "45" );
System.out.println( "通过构造器的方式创建的JSONObject对象:" +obj);
Map<String,String> map= new LinkedHashMap<>();
map.put( "derek" , "23" );
map.put( "dad" , "49" );
map.put( "mom" , "45" );
System.out.println( "通过fromObject方法将map对象转换为JSONObject对象:" +JSONObject.fromObject(map));
JSONArray arr= new JSONArray();
arr.add( 0 , "derek" );
arr.add( 1 , "dad" );
arr.add( 2 , "mom" );
System.out.println( "通过构造器的方式创建的JSONArray:" +arr);
ArrayList<String> list= new ArrayList<>();
list.add( "derek" );
list.add( "dad" );
list.add( "mom" );
System.out.println( "通过fromObject方法将Arraylist对象转换为JSONArray对象:" +JSONArray.fromObject(list));
System.out.println( "将HashMap对象通过fromObject方法转换为JSONArray对象" +JSONArray.fromObject(map));
String str= "{\"derek\":23,\"dad\":49,\"mom\":45}" ;
System.out.println( "解析之后的JSON对象:" +JSONObject.fromObject(str));
//遍历输出
Iterator<String> it=obj.keys();
while (it.hasNext()){
String key=it.next();
System.out.println(key+ ":" +obj.get(key));
}
}
} |
运行结果如下:
通过构造器的方式创建的JSONObject对象:{"derek":"23","dad":"49","mom":"45"}
通过fromObject方法将map对象转换为JSONObject对象:{"derek":"23","dad":"49","mom":"45"}
通过构造器的方式创建的JSONArray:["derek","dad","mom"]
通过fromObject方法将Arraylist对象转换为JSONArray对象:["derek","dad","mom"]
将HashMap对象通过fromObject方法转换为JSONArray对象[{"derek":"23","dad":"49","mom":"45"}]
解析之后的JSON对象:{"derek":23,"dad":49,"mom":45}
derek:23
dad:49
mom:45