Json是一种轻量级的数据交换格式,它是一种完全独立于编程语言的文本格式来存储和表示数据,简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。Json由键值对组成,其中键必须带双引号,值可以是基本的数据类型,数值类型,字符串,布尔类型等,json可可以相互嵌套,常见的有json对象和json数组
//Json对象
{
"name": "zhang",
"age": 23,
"isStudent": true,
"majors": ["Math", "English"]
}
//Json数组
[
{
"name":"li",
"age":24,
"isStudent":true,
"majors":["Math","English","Chinese"]
},
{
"name":"zhang",
"age":23,
"isStudent":true,
"majors":["Math","English"]
}
]
使用IO流读取本地的Json文件,并将其转换为对象或对象的集合
IO流读取文件工具类
@Slf4j
public class FileUtils {
private static final String SUFFIX = ".json";
/**
* 按字节流读取文件
* @param fileName
* @param path
* @return
*/
public static String readWithByte(String fileName,String path){
String fullPath = joinPath(fileName, path);
File file = readValidate(fullPath);
StringBuffer sbuffer = new StringBuffer();
try {
FileInputStream inputStream = new FileInputStream(file);
byte[] bytes = new byte[1024];
int len = -1;
while ((len = inputStream.read(bytes,0,bytes.length)) != -1){
sbuffer.append(new String(bytes,0,len,"UTF-8"));
}
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException error){
error.printStackTrace();
}
return sbuffer.toString();
}
/**
* 字节缓冲流读取
* @param fileName
* @param path
* @return
*/
public static String readWithByteBuffer(String fileName,String path){
String fullPath = joinPath(fileName, path);
File file = readValidate(fullPath);
StringBuffer sbuffer = new StringBuffer();
try {
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
byte[] bytes = new byte[1024];
int len = -1;
while ((len = bufferedInputStream.read(bytes,0,bytes.length)) != -1){
sbuffer.append(new String(bytes,0,len,"UTF-8"));
}
bufferedInputStream.close();
}catch (Exception error){
error.printStackTrace();
}
return sbuffer.toString();
}
/**
* 字符缓冲流读取
* @param fileName
* @param path
* @return
*/
public static String readWithStreamReader(String fileName,String path){
String fullPath = joinPath(fileName, path);
File file = readValidate(fullPath);
StringBuffer sbuffer = new StringBuffer();
String str;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
while ((str = reader.readLine()) != null){
sbuffer.append(str);
}
reader.close();
}catch (Exception error){
error.printStackTrace();
}
return sbuffer.toString();
}
private static File readValidate(String fullPath){
File file = new File(fullPath);
if(!file.exists()){
log.error("can not find file,file path ={}",fullPath);
}
return file;
}
private static String joinPath(String fileName,String path){
String fullPath = null;
if(path.endsWith("/")){
fullPath = path + fileName + SUFFIX;
}else {
fullPath = path + "/" + fileName + SUFFIX;
}
return fullPath;
}
}
按照Json的数据结构和字段定义实体类,用于接收读取的Json数据,使用jackson(还有很多其他的json转换工具包,如FastJson,Gson等)将Json转换为实体对象
@Data
@NoArgsConstructor
public class StudentDomain implements Serializable{
private static final long serialVersionUID = -2941038235085595087L;
private String name;
private Integer age;
private Boolean isStudent;
private List<String> majors;
}
@Service
public class JsonFileService {
@Autowired
private ObjectMapper mapper;
/**
* 读取json对象,转domain
* @param fileName
* @param path
* @return
*/
public String readJsonToDomain(String fileName,String path){
String source = FileUtils.readWithByteBuffer(fileName, path);
try {
StudentDomain studentDomain = mapper.readValue(source, StudentDomain.class);
return studentDomain.toString();
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
/**
* 读取json集合,转domain list
* @param fileName
* @param path
* @return
*/
public List readJsonToDomains(String fileName,String path){
String source = FileUtils.readWithByteBuffer("students", "F:\\Project\\spring-tutorials\\spring-io");
try {
//使用TypeReference也可以实现转换
// List<StudentDomain> students = mapper.readValue(source, new TypeReference<List<StudentDomain>>(){});
CollectionType collectionType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, StudentDomain.class);
List<StudentDomain> list = mapper.readValue(source, collectionType);
return list;
}catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
}
本地Json文件内容student.json
{
"name":"zhang",
"age":23,
"isStudent":true,
"majors":["Math","English"]
}
students.json
[
{
"name":"li",
"age":24,
"isStudent":true,
"majors":["Math","English","Chinese"]
},
{
"name":"zhang",
"age":23,
"isStudent":true,
"majors":["Math","English"]
}
]
编写测试用例,测试转换效果:
@SpringBootTest
public class SpringIoApplicationTests {
@Autowired
private JsonFileService service;
@Test
public void readFileToDomainTest(){
String result = service.readJsonToDomain("student","F:\\Project\\spring-tutorials\\spring-io");
System.out.println("Context:" + result);
}
@Test
public void readFileToDomainsTest(){
List resultList = service.readJsonToDomains("students","F:\\Project\\spring-tutorials\\spring-io");
System.out.println("resultList:" + resultList);
}
}
输出结果:
只要数据格式和自定义的实体对象字段、数据类型一致都可以实现相互转换,此外Json也还可以和Map进行很好的相互转换。