首页 > 代码库 > Json基本用法
Json基本用法
1 Data类(获取要转化为json的数据)
package org.data;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Data {
public List<String> getList(){
List<String> list = new ArrayList<String>();
list.add( "xixi" );
list.add( "haha" );
list.add("sb");
return list;
}
public Map<String, String> getMap(){
Map<String, String> map = new HashMap<String, String>();
map.put("name", "晓波哥");
map.put("sex", "男");
map.put("age", "无限");
map.put("另一半", "暂无");
map.put("初恋", "跑了");
return map;
}
public boolean[] getArray(){
boolean[] boolArray = new boolean[] { true, false, true };
return boolArray;
}
}
2Bean(javabean也可以转化为json)注:要加上getter和setter
package org.data;
public class JsonBean {
private String name;
private String sex;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public JsonBean(String a,String b ,String c){
this.setName(a);
this.setSex(b);
this.setAge(b);
}
}
3测试类
package org.data;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class ParseJsonTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Data data=http://www.mamicode.com/new Data();
List list=data.getList();
Map map=data.getMap();
boolean[] b=data.getArray();
JSONArray jsonArrayfromList = JSONArray.fromObject( list );
JSONObject jsonObjectfromMap = JSONObject.fromObject(map);
JSONArray jsonArrayfromArray = JSONArray.fromObject(b);
System.out.println(jsonArrayfromList);
System.out.println(jsonObjectfromMap);
System.out.println(jsonArrayfromArray);
JSONArray jsonArrayfromString= JSONArray.fromObject("[‘json‘,‘is‘,‘easy‘]" );
System.out.println(jsonArrayfromString);
JSONObject jsonObjectfromBean = JSONObject.fromObject(new JsonBean("晓波哥", "男", "23"));
System.out.println(jsonObjectfromBean);
}
}
4截图
5所需jar包(下载json-lib文件夹即可)
Json基本用法