如何在java中读取多个Json

时间:2018-03-29 09:47:03

标签: java json

使用以下代码我得

{"User_id":"test123","Password":"test225"}{"User_id":"test122","Password":"asds"}

无效的json格式

其实我想要json的格式,但我无法创建        **

[{“User_id”:“test123”,“密码”:“test225”},{“User_id”:“test122”,“密码”:“asds”}]

**

这是我的json创建代码

 String Filename="json_log_text";
       JSONObject jobject=new JSONObject();
       jobject.put("User_id",jTextField1.getText());
       jobject.put("Password",jPasswordField1.getText());

       FileWriter writer=new FileWriter(("D:\\file store\\"+Filename+".txt"),true);
       writer.write(jobject.toJSONString());
       writer.flush();

2 个答案:

答案 0 :(得分:0)

[{"User_id":"ss","Password":"ssss"}] [{"User_id":"abc","Password":"ss"}] [{"User_id":"jk","Password":"aa"}]的格式与任何JSON data types都不匹配。

尝试将其转换为数组:

[{"User_id":"ss","Password":"ssss"},{"User_id":"abc","Password":"ss"},{"User_id":"jk","Password":"aa"}]

答案 1 :(得分:0)

这里我有解决方案阅读多次阅读json时粘贴代码以便将来帮助某人,为此我使用 json-simple-1.1.1.jar

import java.io.*;
import java.io.FileWriter;  
import java.io.FileOutputStream.*;
import java.io.OutputStreamWriter.*;
import java.io.FileNotFoundException;
import java.nio.file.Path;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
json写

String Filename="json_log_text";
       JSONObject jobject=new JSONObject();
       JSONArray jarray=new JSONArray();
       jobject.put("User_id",jTextField1.getText());
       jobject.put("Password",jPasswordField1.getText());
       jarray.add(jobject);

   FileWriter writer=new FileWriter(("D:\\file store\\"+Filename+".txt"),true);
   writer.write(jobject.toJSONString());
   writer.flush();

Json Read

 String user_id=jTextField1.getText();
  String Password=jPasswordField1.getText();

              String Filename1="json_log_text_parse";
           JSONParser parser=new JSONParser();



            JSONObject jobject1=new JSONObject();
           JSONArray jarray1=new JSONArray();
            jobject1.put("User_id",jTextField1.getText());
       jobject1.put("Password",jPasswordField1.getText());
       jarray1.add(jobject1);
       FileWriter writer1 =new FileWriter(Filename,true);
       BufferedWriter bf2=new BufferedWriter(writer1);
       PrintWriter pw=new PrintWriter(bf2);

       pw=new PrintWriter(new FileOutputStream(new File("D:\\file store\\"+Filename1+".txt"),true));



              for (Object o:jarray1)
           {

               JSONObject jsonobject=(JSONObject) o;


                user_id=(String) jsonobject.get("User_id");
               pw.print("User_id:"+user_id+"\n");


              Password=(String) jsonobject.get("Password");
               pw.print("Password:"+Password+"\n");



           }

                pw.println();
                pw .close();