Java 读取Json文件转Domain

1 篇文章 0 订阅
1 篇文章 0 订阅

 

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进行很好的相互转换。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值