看到网上有人用jason-lib这个库,我就选择了它!开始学习的时候碰到了一些问题,但只要按照要求配置好下面四个依赖库就可以写测试代码了。 jakarta commons-lang 2.3 jakarta commons-beanutils 1.7.0 jakarta commons-collections 3.2 jakarta commons-logging 1.1.1 ezmorph 1.0.4 然后按照网站上的getting started进行学习,碰到的第一个问题就是在处理bean的转换的时候总是报告"has no getter method",找了好久才知道, 错误的原因是要转换的bean必须是public的。 下面是我找到的学习资料:
相关链接: http://json-lib./ http://ezmorph./ http://morph./
使用过程中问题: 1,把bean转化为json格式时老提示如下错误: Exception in thread "main" net.sf.json.JSONException: java.lang.NoSuchMethodException: Property 'name' has no getter method 解决:声明bean为public class xxx,必须是public,我用默认类型(class xxx)都不行
2,Exception in thread "main" java.lang.NoSuchMethodError: org.apache.commons.lang.ArrayUtils.toObject([C)[Ljava/lang/Character; 原因:定义属性如下:private char[] options = new char[] { 'a', 'f' };好像不能处理这种类型的
3, private String func1 = "function(i){ return this.options[i]; }"; 和 private JSONFunction func2 = new JSONFunction(new String[] { "i" }, "return this.options[i];"); 转换后显示结果差不多: {"func1":function(i){ return this.options[i];,"func2":function(i){ return this.options[i]; }}
测试类:
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
-
- import net.sf.json.JSONArray;
- import net.sf.json.JSONObject;
-
- public class Json {
- public static void main(String[] args) {
- Json j = new Json();
- j.bean2json();
- }
-
- public void arr2json() {
- boolean[] boolArray = new boolean[] { true, false, true };
- JSONArray jsonArray = JSONArray.fromObject(boolArray);
- System.out.println(jsonArray);
-
- }
-
- public void list2json() {
- List list = new ArrayList();
- list.add("first");
- list.add("second");
- JSONArray jsonArray = JSONArray.fromObject(list);
- System.out.println(jsonArray);
-
- }
-
- public void createJson() {
- JSONArray jsonArray = JSONArray.fromObject("['json','is','easy']");
- System.out.println(jsonArray);
-
- }
-
- public void map2json() {
- Map
- map.put("name", "json");
- map.put("bool", Boolean.TRUE);
- map.put("int", new Integer(1));
- map.put("arr", new String[] { "a", "b" });
- map.put("func", "function(i){ return this.arr[i]; }");
-
- JSONObject json = JSONObject.fromObject(map);
- System.out.println(json);
-
-
-
- }
-
- public void bean2json() {
- JSONObject jsonObject = JSONObject.fromObject(new MyBean());
- System.out.println(jsonObject);
-
-
-
-
-
-
- }
-
- public void json2bean() {
- String json = "{name=\"json2\",func1:true,pojoId:1,func2:function(a){ return a; },options:['1','2']}";
- JSONObject jb = JSONObject.fromString(json);
- JSONObject.toBean(jb, MyBean.class);
- System.out.println();
- }
- }
操作的bean:
- import net.sf.json.JSONFunction;
-
- public class MyBean {
- private String name = "json";
- private int pojoId = 1;
-
- private String func1 = "function(i){ return this.options[i]; }";
- private JSONFunction func2 = new JSONFunction(new String[] { "i" },
- "return this.options[i];");
-
-
- ......
- }
|