Map, JavaBean ,字符串 转化为JSON
/*Map转化为json*/
static public void test1() {
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("name", "youyuan");
JSONObject jsonObject = new JSONObject(hashMap);
System.out.println(jsonObject);
}
/*javaBean转化为json*/
static public void test2() {
Person person = new Person("1", "zs", 22);
JSONObject jsonObject = new JSONObject(person);
System.out.println(jsonObject);
}
/*字符串转化为json*/
static public void test3() {
String json = "{\"name\":\"zs\",\"id\":\"1\",\"age\":22}";
JSONObject jsonObject = new JSONObject(json);
System.out.println(jsonObject);
}
将文件转化成json
/*将文件转化成json
* 文件-->字符串
* 字符串-->json
* 方法一*/
static void test4() throws IOException {
FileInputStream inputStream = new FileInputStream("src/main/resources/person.json");
byte[] bytes = new byte[1024];
StringBuffer stringBuffer =new StringBuffer();
int len =-1;
while ((len = inputStream.read(bytes)) != -1){
stringBuffer.append(new String(bytes),0,len);
}
JSONObject jsonObject = new JSONObject(stringBuffer.toString());
System.out.println(jsonObject);
}
/** 方法二,使用类加载器*/
void test5() throws IOException {
InputStream inputStream = super.getClass().getClassLoader().getResourceAsStream("person.json");
byte[] bytes = new byte[1024];
StringBuffer stringBuffer =new StringBuffer();
int len =-1;
while ((len = inputStream.read(bytes)) != -1){
stringBuffer.append(new String(bytes),0,len);
}
JSONObject jsonObject = new JSONObject(stringBuffer.toString());
System.out.println(jsonObject);
}
直接使用工具类
//文件变字符串
String s = FileUtils.readFileToString(new File("E:\\IDEA工程\\json\\json\\src\\main\\resources\\person.json"));
System.out.println(s);
生成json文件
/*生成json文件*/
public void test6() throws IOException {
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("name", "youyuan");
hashMap.put("id", UUID.randomUUID().toString());
JSONObject jsonObject = new JSONObject(hashMap);
//将数据写入到文件当中
FileWriter writer = new FileWriter("G:\\json.txt");
jsonObject.write(writer);
writer.close();
}