无论是前端还是后端, java开发中经常使用到 json 格式数据
1,json 的语法如下图:
2,java 后端中操作 json格式的类为 net.sf.json.JSONObject,常用的 api 有:
public static void main(String[] args) {
// 创建一个JSONObject对象
JSONObject jsonObject = new JSONObject();
// 将一个对象转换为JSONObject对象
Map<String, String> map = new HashMap<String, String>();
map.put("we", "dsds");
JSONObject jsonObject2 = JSONObject
.fromObject(map);
JSONObject jsonObject3 = JSONObject.fromObject(new Person());
JSONObject jsonObject4 = JSONObject
.fromObject("{obj: [{name: 'wwp'}, {age: 22}], obj: 2}");
//将一个JSONObject对象转换为其它类型
Map<String, String> map2 = (Map)JSONObject.toBean(jsonObject2, Map.class);
Person person = (Person)JSONObject.toBean(jsonObject3, Person.class);
//获取JSONObject对象 键的集合
for(Object o: jsonObject4.keySet()){
System.out.println(jsonObject4.get("obj"));
}
//put() 和 get() 方法
jsonObject2.put("key", "sds");
jsonObject2.get("key"); //注意:如果键不存在,则抛出异常
}
3,json 和 xml 之间的相互转换
转换 xml 格式数据为 json 格式
package jsontest;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;
public class jsonTest {
public static void main(String[] args) {
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><user_info><password>123456</password><username>张三</username></user_info>";
XMLSerializer xSerializer = new XMLSerializer();
JSON json = xSerializer.read(xml);
JSONObject jsonObject = JSONObject.fromObject(json);
System.out.println(jsonObject.get("password33"));
}
}
json 格式数据转换为 xml 格式:
package jsontest;
import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;
public class jsonTest {
public static void main(String[] args) {
XMLSerializer xSerializer = new XMLSerializer();
JSONObject jsonObject = JSONObject.fromObject("{name: 'wwp', password: 'sddw'}");
xSerializer.setRootName("userInfo");
xSerializer.setTypeHintsEnabled(false);
String json = xSerializer.write(jsonObject);
System.out.println(json);
}
}
4,json 与 java 对象之间的相互转换
将java 对象中的 日期对象转换为 特定字符串格式方法:
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonValueProcessor(Date.class, new JsonValueProcessor() {
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Override
public Object processObjectValue(String arg0, Object date, JsonConfig arg2) {
return sdf.format(date);
}
@Override
public Object processArrayValue(Object date, JsonConfig arg1) {
return sdf.format(date);
}
});
JSONObject json = JSONObject.fromObject(school, jsonConfig);
json –> bean ,如果bean中有其它类的集合,可以使用如下方法解决:
Map<String, Object> mapClass = new HashMap<String, Object>();
mapClass.put("classRooms", ClassRoom.class);
mapClass.put("students", Student.class);
School sch = (School) JSONObject.toBean(json, School.class, mapClass);
System.out.println(sch.getClassRooms().get(0).getStudents().get(0).getBirthday());