当前位置: 代码迷 >> JavaScript >> java 跟json的操作
  详细解决方案

java 跟json的操作

热度:426   发布时间:2012-09-19 13:43:54.0
java 和json的操作

public class Test {//测试
?public static void main(String[] args){
??getStr();
??getList();
??getMap();
??getObject();
?}
?
?public static void getStr(){//string数组转化成Json
??String[] str ={"1","2","3","4"};
??JSONArray jsonArray = JSONArray.fromObject(str);
??System.out.println(jsonArray);
??
?}
?public static void getList(){//list转化成Json
??List list = new ArrayList();
??String[] str ={"1","2","3","4"};
??list.add(str);
??list.add("adfasdfasd");
??JSONArray jsonArray = JSONArray.fromObject(list);
??System.out.println(jsonArray);
?}
?
?public static void getMap(){//map数组转化成Json
??Map map = new HashMap();
??String[] str ={"1","2","3","4"};
??map.put("aa", "a");
??map.put("bb", "b");
??map.put("cc", "c");
??map.put("dd", "d");
??map.put("ee", "e");
??map.put("str", str);
??JSONArray jsonArray = JSONArray.fromObject(map);
??jsonArray.add("BBBBBBBBBBBBBBBB");
??
??System.out.println(jsonArray);
??System.out.println(jsonArray.getString(1));
?}
?
?public static void getObject(){
??String str ="{'name':'aaaaaaaa','age':33}";
??JSONObject jsonObject = JSONObject.fromObject(str);
??System.out.println(jsonObject);
??Person person = (Person)JSONObject.toBean(jsonObject,Person.class);
??System.out.println(person.getName());
??
?}
}

  相关解决方案