原文地址:JSONObject.fromObject(map)(JSON与JAVA数据的转换)作者:田保兴
JSON与JAVA数据的转换(JSON 即 JavaScript Object Natation,它是一种轻量级的数据交换格式,非常适合于服务器与 JavaScript 的交互。)
JSONObject jo = JSONObject.fromObject(map); 常见的java代码转换成json
1. List集合转换成json代码
List list = new ArrayList();
list.add( "first" );
list.add( "second" );
JSONArray jsonArray2 = JSONArray.fromObject( list );
2. Map集合转换成json代码
Map map = new HashMap();
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);
3. Bean转换成json代码
JSONObject jsonObject = JSONObject.fromObject(new JsonBean());
4. 数组转换成json代码
boolean[] boolArray = new boolean[] { true, false, true };
JSONArray jsonArray1 = JSONArray.fromObject(boolArray);
5. 一般数据转换成json代码
JSONArray jsonArray3 = JSONArray.fromObject("[‘json‘,‘is‘,‘easy‘]" );
实例代码:
public static void main(String[] args) {
Map map=new HashMap();
map.put("我","是");
map.put("好","孩");
map.put("子","呀");
JSONObject json = JSONObject.fromObject(map);
System.out.println(json); }
输出的結果 {"我":"是","好":"孩","子":"呀"}
toBean();
首先一个javabean对象
public class Student {
private int id ;
private String name;
private int age;
/*各属性的get和set方法*/
public String toString(){
return this.id + ", " + this.name + ", " + this.age; } }
然后测试toBean方法的类 import net.sf.json.JSONObject;
public class ToBeanTest {
public static void main(String[] args) {
String json = "{id:‘1001‘,name:‘张三‘,age:‘22‘}";
Student stu = new Student();
JSONObject obj = JSONObject.fromObject(json);
stu =
(Student)JSONObject.toBean(obj, Student.class);
System.out.println(stu); }
}
输出结果为1001, 张三, 22