json的写入和解析(读取)
原创
©著作权归作者所有:来自51CTO博客作者B.Y的原创作品,请联系作者获取转载授权,否则将追究法律责任
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 {
JsonObject jo=new JsonObject();
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
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())
}
}