Detailed description of how Java reads and writes files in json format

Source: Internet
Author: User

I. What is the json format first to solve this problem?

JSON format:
For example, a student has a student ID, name, and gender.
In json format:
{"Studno": "11111", "studname": "wwww", "studsex": "male"} (all fields are of the struct type)

This indicates the information of a student.

What if there are more?

[{"Studno": "122222", "studname": "wwww", "studsex": "male "},
{"Studno": "11111", "studname": "xxxx", "studsex": "male "},
{"Studno": "33333", "studname": "ssss", "studsex": "male"}]

This is the json format.

2. How to operate a file in json format?

This is simpler. To put it bluntly, you can directly read and write the file, and then format the content of the read file into json.

3. Specific operations.

1. I have an entity class, as shown below:

Public class ElectSet {
Public String xueqi;
Public String xuenian;
Public String startTime;
Public String endTime;
Public int menshu;
Public String isReadDB;
// {"Xueqi":, "xuenian":, "startTime":, "endTime":, "renshu":, "isReadDB ":}
Public String getXueqi (){
Return xueqi;
}
Public void setXueqi (String xueqi ){
This. xueqi = xueqi;
}
Public String getXuenian (){
Return xuenian;
}
Public void setXuenian (String xuenian ){
This. xuenian = xuenian;
}
Public String getStartTime (){
Return startTime;
}
Public void setStartTime (String startTime ){
This. startTime = startTime;
}
Public String getEndTime (){
Return endTime;
}
Public void setEndTime (String endTime ){
This. endTime = endTime;
}
Public int getMenshu (){
Return menshu;
}
Public void setMenshu (int menshu ){
This. menshu = menshu;
}
Public String getIsReadDB (){
Return isReadDB;
}
Public void setIsReadDB (String isReadDB ){
This. isReadDB = isReadDB;
}

}

2. There is a json file that stores its information, as shown below:

Sets. json:
{"Xuenian": "2007-2008", "xueqi": "1", "startTime": "", "endTime ", "menshu": "10", "isReadDB": "Y "}

3. Specific operations.
/*
* Retrieve the file content and fill in the object
*/
Public ElectSet findElectSet (String path ){
ElectSet electset = new ElectSet ();
String sets = ReadFile (path); // get the content of the json File
JSONObject jo = JSONObject. fromObject (sets); // formatted as a json object
// System. out. println ("------------" jo );
// String name = jo. getString ("xuenian ");
// System. out. println (name );
Electset. setXueqi (jo. getString ("xueqi "));
Electset. setXuenian (jo. getString ("xuenian "));
Electset. setStartTime (jo. getString ("startTime "));
Electset. setEndTime (jo. getString ("endTime "));
Electset. setMenshu (jo. getInt ("menshu "));
Electset. setIsReadDB (jo. getString ("isReadDB "));
Return electset;
}
// Set Properties and save
Public boolean setElect (String path, String sets ){
Try {
WriteFile (path, sets );
Return true;
} Catch (IOException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
Return false;
}
}
// Read the file and return a string
Public String ReadFile (String path ){
File file = new File (path );
BufferedReader reader = null;
String laststr = "";
Try {
// System. out. println ("read the file content in the unit of action, read the entire line at a time :");
Reader = new BufferedReader (new FileReader (file ));
String tempString = null;
Int line = 1;
// Read a row at a time until null is the end of the file.
While (tempString = reader. readLine ())! = Null ){
// Display the row number
System. out. println ("line" line ":" tempString );
Laststr = laststr tempString;
Line;
}
Reader. close ();
} Catch (IOException e ){
E. printStackTrace ();
} Finally {
If (reader! = Null ){
Try {
Reader. close ();
} Catch (IOException e1 ){
}
}
}
Return laststr;
}
// Write a json string to a file
Public void writeFile (String filePath, String sets) throws IOException {
FileWriter fw = new FileWriter (filePath );
PrintWriter out = new PrintWriter (fw );
Out. write (sets );
Out. println ();
Fw. close ();
Out. close ();
}

4. Call and use (called in the website controller)

// Retrieve the json object
Public void GetElectSettings (HttpServletRequest request,
HttpServletResponse response) throws Exception {
ElectSet electset = new ElectSet ();
String absPath = request. getRealPath ("\");
String filePath = absPath "public \ sets \ electSets. json ";
Electset = businessService. findElectSets (filePath); // It is called here. You can modify it yourself. I call the business layer.
JSONArray jsonItems = new JSONArray ();
JsonItems. add (electset );
JSONObject jo = new JSONObject ();
Jo. put ("data", jsonItems );
System. out. println (jo );
Request. setCharacterEncoding ("UTF-8 ");
Response. setContentType ("application/json; charset = UTF-8 ");
PrintWriter out = response. getWriter ();
Out. print (jo );
}

// Modify the json File
Public void ChangeElectSet (HttpServletRequest request,
HttpServletResponse response) throws Exception {
Request. setCharacterEncoding ("UTF-8 ");
Response. setContentType ("text/json; charset = UTF-8 ");
Log.info ("reach ChangeElectSet ");
String json = (String) request. getParameter ("json"). trim ();
Log.info ("Change ElectSet ");
Log.info (json );
ElectSet sets = new ElectSet ();
JSONObject jsonObject = JSONObject. fromObject (json );
Sets = (ElectSet) JSONObject. toBean (jsonObject, ElectSet. class );
If (sets. getIsReadDB () = "false "){
Sets. setIsReadDB ("no ");
}
Else {
Sets. setIsReadDB ("yes ");
}
String changes = "{" xuenian ":" "; // use" escape "because json attributes must be enclosed in quotation marks.
Changes = sets. getXuenian () "", "xueqi": "" sets. getXueqi () "", "startTime": "" sets. getStartTime () "", "endTime": "" sets. getEndTime () "", "menshu": "" sets. getMenshu () "", "isReadDB": "" sets. getIsReadDB ()""}";
System. out. println (changes );
String absPath = request. getRealPath ("\");
String filePath = absPath "public \ sets \ electSets. json ";

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.