當前位置:編程學習大全網 - 熱門推薦 - json lib.jar怎麽使用

json lib.jar怎麽使用

json-lib.jar開發包使用:

依賴包:

commons-beanutils.jar;

commons-mons-lang.jar;

ezmorph.jar;不少人使用時會提示net.sf.ezmorph.xxx找不到,就是缺這個:

morph-1.0.1.jar

使用過程中問題:

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);

// prints [true,false,true]

}

public void list2json() {

List list = new ArrayList();

list.add("first");

list.add("second");

JSONArray jsonArray = JSONArray.fromObject(list);

System.out.println(jsonArray);

// prints ["first","second"]

}

public void createJson() {

JSONArray jsonArray = JSONArray.fromObject("['json','is','easy']");

System.out.println(jsonArray);

// prints ["json","is","easy"]

}

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);

// prints

// ["name":"json","bool":true,"int":1,"arr":["a","b"],"func":function(i){

// return this.arr[i]; }]

}

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();

}

}

  • 上一篇:sns是什麽
  • 下一篇:有個性的名字
  • copyright 2024編程學習大全網