java json的序列化和反序列化

1、json字符串反序列化

(1)获取字符串

/**
     * 读取json文件,返回json串
     * @param fileName
     * @return
     */
    public static String readJsonFile(String fileName) {
        String jsonStr = "";
        try {
            File jsonFile = new File(fileName);
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return jsonStr;
    }

(2)反序列化

添加依赖

>
	>com.alibaba>
	>fastjson>
	>1.2.47>
 >

代码

import com.alibaba.fastjson.JSONObject;

Evaluation evaluation = JSONObject.parseObject(jsonStr, Evaluation.class);

Evaluation是自定义的对象

2、java对象序列化为json字符串

//todo 待补充

你可能感兴趣的:(java,json,开发语言)