|
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
|
package
com.hanchao.web;
import
net.sf.json.JSONArray;
import
net.sf.json.JSONObject;
/***********************
* java解析json
* @author:han
* @version:1.0
* @created:2013-8-28
***********************
*/
public
class
TestJson {
public
static
void
main(String[] args) {
String json =
"{'id':1,"
+
"'username':{'tom':'tom','jerry':'jerry'},"
+
"'address':[{'us':'usa','cancada':'canada'},{'chi':'china','aus':'aus'}]}"
;
JSONObject jo = JSONObject.fromObject(json);
System.err.println(
"1--:"
+ jo.get(
"id"
));
JSONObject uObject = jo.getJSONObject(
"username"
);
System.out.println(
"2--username:"
+ uObject);
System.out.println(
"2--username:"
+ uObject.get(
"tom"
));
JSONArray addressArray = jo.getJSONArray(
"address"
);
System.out.println(
"3--:"
+ addressArray.getJSONObject(
0
));
System.out.println(
"3--:"
+ addressArray.getJSONObject(
0
).get(
"us"
));
System.out.println(
"3--:"
+ addressArray.getJSONObject(
1
).get(
"chi"
));
}
}
|
结果:
1--:1
2--username:{"tom":"tom","jerry":"jerry"}
2--username:tom
3--:{"us":"usa","cancada":"canada"}
3--:usa
3--:china
============对象转为JSON对象---------------
|
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
|
Map<String, Object> map =
new
HashMap<String, Object>();
map.put(
"id"
,
1
);
map.put(
"username"
,
"hanchao"
);
map.put(
"password"
, 123L);
String toJson = JSONObject.fromObject(map).toString();
System.out.println(
"toJSON:"
+ toJson);
JSONObject jo1 = JSONObject.fromObject(toJson);
System.out.println(
"id:"
+ jo1.getInt(
"id"
) +
", username:"
+ jo1.getString(
"username"
) +
", password:"
+ jo1.getString(
"password"
));
//2014-04-03-把List集合转为JSon数组--------------------------------------------
//方法一:
List<User> list =
new
ArrayList<User>();
User u1 =
new
User();
u1.setId(
1
);
u1.setUsername(
"u1"
);
u1.setPassword(
"p1"
);
User u2 =
new
User();
u2.setId(
2
);
u2.setUsername(
"u2"
);
u2.setPassword(
"p2"
);
list.add(u1);
list.add(u2);
String resultJson = JSONArray.fromObject(list).toString();
System.out.println(
" ========= : "
+ resultJson);
//方法二:
JSONArray array =
new
JSONArray();
for
(User user : list) {
JSONObject obj =
new
JSONObject();
obj.put(
"username"
, user.getUsername());
obj.put(
"id"
, user.getId());
obj.put(
"password"
, user.getPassword());
array.add(obj);
}
String resultJSON2 = array.toString();
System.out.println(
" ========= : "
+ resultJSON2);
|
本文转自韩立伟 51CTO博客,原文链接:http://blog.51cto.com/hanchaohan/1284426
,如需转载请自行联系原作者