您的位置:首页 > 编程语言 > Java开发

json-lib JSON与Java之间转换

2014-07-05 22:43 239 查看
主要使用的jar包

commons-beanutils-1.9.2.jar

commons-collections-3.2.1.jar

commons-lang-2.6.jar

commons-logging-1.1.3.jar

ezmorph-1.0.6.jar

json-lib-2.4-jdk15.jar

主要使用了使用了JSONArray与JSONObject

普通类型、List、Collection等都是用JSONArray解析

Map、自定义类型是用JSONObject解析

涉及的主要代码

public class Student {
private int id;
private int number;
private String name;
private int age;
private Like like;
public Student(int id){
this.like=new Like("basketball","ball");
this.id=id;
this.name="www";
this.age=18;
this.number=20111344;
}
public Student(){
this.like=new Like("basketball","ball");
this.name="www";
this.age=18;
this.number=20111344;
}
}
public class Like {
private String name;
private String type;
public Like(String name,String type){
this.name=name;
this.type=type;
}
}
public class TestMain {
public static void main(String[] args) {
Student student=new Student();
JSONObject jsonObject=JSONObject.fromObject(student);
System.out.println(jsonObject);
}
}


import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONObject;
public class TestMain {
public static void main(String[] args) {
Map<String, String> map=InitMap();
JSONObject jo=JSONObject.fromObject(map);
System.out.println(jo);
}
public static Map<String, String> InitMap(){
Map<String, String> map=new HashMap<String, String>();
map.put("name", "www");
map.put("age", "18");
return map;
}
}


import java.util.ArrayList;
import java.util.List;
import com.wlx.object.Student;
import net.sf.json.JSONArray;
public class TestMain {
public static void main(String[] args) {
String[] array=InitArray();
List<Student> list=InitList();
JSONArray ja1=JSONArray.fromObject(array);
JSONArray ja2=JSONArray.fromObject(list);
System.out.println(ja1);
System.out.println(ja2);
}
public static String[] InitArray(){
String[] array={"a","b","c","d"};
return array;
}
public static List<Student> InitList(){
List<Student> list=new ArrayList<Student>();
Student s1=new Student(1);
Student s2=new Student(2);
Student s3=new Student(3);
Student s4=new Student(4);
Student s5=new Student(5);
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
list.add(s5);
return list;
}
}


import net.sf.json.JSONObject;
public class TestMain {
public static void main(String[] args) {
//字符串转化为JSON格式,并且转化为Java对象
String jsonStr="{\"name\":\"www\",\"job\":{\"name\":\"teacher\"}}";
JSONObject jo=JSONObject.fromObject(jsonStr);
Person s=(Person)JSONObject.toBean(jo,Person.class);
System.out.println(s.getName()+"\n"+s.getJob().getName());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: