生成json格式的字符串。
需要相关包
1 package cn.itcast.controller;
2
3 import static org.junit.Assert.*;
4
5 import java.util.ArrayList;
6 import java.util.List;
7
8 import net.sf.json.JSONArray;
9 import net.sf.json.JSONObject;
10 import net.sf.json.JsonConfig;
11
12 import org.junit.Test;
13
14 import cn.itcast.domain.Province;
15
16 public class JSONlibTest {
17
18 @Test
19 public void test1() {
20 Province p = new Province("山东省","250000");
21 JSONObject jsonObj = JSONObject.fromObject(p);
22 System.out.println(jsonObj.toString());
23 }
24 @Test
25 public void test2() {
26 List<Province> ps = new ArrayList<Province>();
27 ps.add(new Province("安徽省", "001"));
28 ps.add(new Province("浙江省", "002"));
29 ps.add(new Province("江苏省", "003"));
30 JSONArray jsonArr = JSONArray.fromObject(ps);
31 System.out.println(jsonArr.toString());
32 }
33 @Test
34 public void test3() {
35 List<Province> ps = new ArrayList<Province>();
36 ps.add(new Province("安徽省", "001"));
37 ps.add(new Province("浙江省", "002"));
38 ps.add(new Province("江苏省", "003"));
39
40 JsonConfig cfg = new JsonConfig();//JSON串过滤
41 cfg.setExcludes(new String[]{"zipcode"});//不包含的字段列表
42
43 JSONArray jsonArr = JSONArray.fromObject(ps,cfg);
44 System.out.println(jsonArr.toString());
45 }
46 }
jsp页面中
1
2 var data=this.responseText;
3
4 var provinceJson=eval("("+data+")");
json 生成 json字符串,布布扣,bubuko.com
时间: 2024-12-26 07:31:34