json的写入和解析(读取)

来源:互联网 发布:遍历复杂json 编辑:程序博客网 时间:2024/05/04 22:27
package jsonParse;import java.io.FileOutputStream;import java.io.IOException;import com.google.gson.JsonObject;public class JsonWrite {    public static void main(String[] args) throws IOException {        //导入json的jar包并构建路径,实例化json对象        JsonObject jo=new JsonObject();        //添加键值对,创建json文件        jo.addProperty("url", "jdbc:mysql://localhost:3306/user");        jo.addProperty("user", "root");        jo.addProperty("pwd", "root");        FileOutputStream fos=new FileOutputStream("config/conn.json");        fos.write(jo.toString().getBytes());        fos.close();    }}
package jsonParse;import java.io.FileNotFoundException;import java.io.FileReader;import com.google.gson.JsonIOException;import com.google.gson.JsonObject;import com.google.gson.JsonParser;import com.google.gson.JsonSyntaxException;/** * json文件的解析(读取) * @author Administrator * */public class JsonReader {    public static void main(String[] args) throws JsonIOException, JsonSyntaxException, FileNotFoundException {        //实例化解析json的对象        JsonParser jp=new JsonParser();        //解析文件后得到json元素,将元素转为json对象        JsonObject jo=(JsonObject) jp.parse(new FileReader("config/conn.json"));        System.out.println(jo.get("url").getAsString());        System.out.println(jo.get("user").getAsString());        System.out.println(jo.get("pwd").getAsString());    }}
0 0
原创粉丝点击