json学习

1、JSONObject学习

/*
* JSONObject学习之put
*/
@Test
public void test1() {
JSONObject json = new JSONObject();

json.put("name", "dj");
json.put("major", new String[] { "听音乐", "写代码" });
json.put("married", false);
json.put("age", 21);
json.put("presentation", "null");// 处理null的方法,写"null"或者""(空字符串)

System.out.println(json.toString());
}

/*
* JSONObject学习之在JSONObject传入map
*/
@Test
public void test2() {
Map<String, Object> json = new HashMap<String, Object>();

json.put("name", "dj");
json.put("major", new String[] { "听音乐", "写代码" });
json.put("married", false);
json.put("age", 21);
json.put("presentation", "");// 处理null的方法,写"null"或者""(空字符串)

System.out.println(new JSONObject(json));
}

/*
* JSONObject学习之在使用java bean构建对象
*/
@Test
public void test3() {
Student student = new Student();

student.setName("dj");
student.setPresentation("");
student.setMajor(new String[] { "听音乐", "写代码" });
student.setMarried(false);
student.setAge(21);

System.out.println(new JSONObject(student));
}

/*
* 使用commons-io读取文件,
* 然后读取到的数据放在jsonObject中
*/
@Test
public void test4() throws Exception {
File file =
new File(Demo.class.getResource("/dj.json").getFile());
String content = FileUtils.readFileToString(file);
JSONObject json = new JSONObject(content);
System.out.println(json);
}

###2、json类库之gson学习

/*
* gson的使用,将PO对象转换成json格式
*/
@Test
public void test1(){
Student student = new Student();

student.setName("dj");
student.setPresentation("");
student.setMajor(new String[] { "听音乐", "写代码" });
student.setMarried(false);
student.setAge(21);
student.setIgnore("haha");

GsonBuilder gsonBuilder = new GsonBuilder(); //创建GsonBuilder
gsonBuilder.setPrettyPrinting(); //格式化JSON格式
// 在转化之前可以插入一个回调函数进行操作
gsonBuilder.setFieldNamingStrategy(new FieldNamingStrategy() {

public String translateName(Field f) {
if(f.getName().equals("name")){
return "NAME";
}
return f.getName();
}
});
Gson gson = gsonBuilder.create(); //创建Gson
String json = gson.toJson(student); //将Gson转化为JSON
System.out.println(json);
}

/*
* commons-io读取文件后
* 将json格式转化成PO对象
*/
@Test
public void test2() throws IOException{
File file =
new File(Demo.class.getResource("/dj.json").getFile());
String content = FileUtils.readFileToString(file);
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
Student student = gson.fromJson(content, Student.class);
System.out.println(student.toString());
}

原文地址:https://www.cnblogs.com/daijun/p/6479977.html