【问题标题】:Problem in code while parsing Json string in Java在 Java 中解析 Json 字符串时出现代码问题
【发布时间】:2021-06-23 02:01:00
【问题描述】:

我是Java 的新手,我使用的是python,编码对我来说是不同的。我正在尝试使用 java 进行字符串计数,我在执行时遇到问题它没有更新我的 json 文件的值它在子目录中创建另一个文本这是我的代码:

package sender;
import java.util.Iterator;
import java.util.Scanner; // import the Scanner class

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import java.io.*;
public class contar {

    public static void main(String[] args) throws ParseException, IOException {
        Scanner myObj = new Scanner(System.in);
        String userName;
        char[] cadena;
        char caracter;
        // Enter username and press Enter
        System.out.println("Enter username"); 
        userName = myObj.nextLine();   
        cadena = userName.toCharArray();     
        boolean[] yaEstaElCaracter = new boolean[Character.MAX_VALUE];
        int[] cuantasVeces = new int[Character.MAX_VALUE];

        for(int i =0;i<cadena.length;i++){
            caracter = cadena[i];
            System.out.println(caracter);
            if(cadena[i]==caracter){
                cuantasVeces[caracter]++;
            }
            yaEstaElCaracter[caracter] = true;
        }//Fin Para
        //Crea el json
        Object a;
        Object b;
        JSONObject jsd = new JSONObject();  
        jsd.put("listado","2");
        JSONArray list = new JSONArray();
        JSONObject obj = new JSONObject();
        for(int i = 0; i < yaEstaElCaracter.length; i++){
            if(yaEstaElCaracter[i]) {
                a= (char) i;
                b = cuantasVeces[i];
                //JSONObject jsd = new JSONObject();   
                /*jsd.put("listado","2");
                JSONArray list = new JSONArray();
                JSONObject obj = new JSONObject();*/
                obj.put((char) i,cuantasVeces[i] );
                
                
                
                
                System.out.println((char) i +" "+cuantasVeces[i]+" veces.");
        
            }
        }
        list.add(obj);
        jsd.put("frecuencias", list);
        
        
        File l = new File("C:\\Users\\andre\\Documents\\9SEMENESTRE\\FATIGA\\tarea");
        
        String[] bus = l.list();
        
        if (bus == null || bus.length == 0) {
            System.out.println("No hay elementos dentro de la carpeta actual");

            try (FileWriter file = new FileWriter("C:\\Users\\andre\\Documents\\9SEMENESTRE\\FATIGA\\tarea\\Reporte.json")){
                file.write(jsd.toString());
                file.flush();
                file.close();
                
            }catch(Exception e) {}
        }else {
            JSONParser jsonParser = new JSONParser();
            
            try (FileReader reader = new FileReader("C:\\Users\\andre\\Documents\\9SEMENESTRE\\FATIGA\\tarea\\Reporte.json"))
            {
                
                Object abc = jsonParser.parse(reader);
     
                JSONObject letras = (JSONObject) abc;
              
                
                JSONArray lang = (JSONArray) letras.get("frecuencias");
                
               
               for (int k = 0; k < lang.size(); k++) {
                    System.out.println("The " + k + " element of the array: " + lang.get(k));
                }
                Iterator k = lang.iterator();
     
                JSONObject jsonObject = new JSONObject(contents.trim());
                Iterator<String> keys = jsonObject.keys();

                while(keys.hasNext()) {
                    String key = keys.next();
                    if (jsonObject.get(key) instanceof JSONObject) {
                          JSONArray     
                    }
                }
                while (k.hasNext()) {
                    JSONObject innerObj = (JSONObject) k.next();
                    for (int i = 0; i < innerObj.size(); i++) {
                        System.out.println(i);
                    }
                    //System.out.println(innerObj.get(cadena.toString()));
                    
                }

                
                //Iterate over employee array
                //employeeList.forEach( emp -> parseEmployeeObject( (JSONObject) emp ) );
     
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            }
            
            
            
            
            

        }
       
        }

}

这是我的输出:

{"listado":"2","frecuencias":[{" ":6,"a":4,"c":2,"d":2,"e":3,"g":1,"i":4,"m":3,"o":5,"p":1,"q":1,"r":2,"s":1,"t":1,"u":1,"y":1}]}{"a":6,c":2,"d":2,"e":3,} <---- I don't need this just update it

【问题讨论】:

  • 那么,您尝试存储一个列表,然后每次运行脚本时检索、更新并再次存储新值?
  • 是的,这正是我想要做的
  • “在子目录中创建另一个文本”:这是什么意思?
  • 报告是这样的 {"listado":"2","frecuencias":[{" ":6,"a":4,"c":2,"d": 2,"e":3,"g":1,"i":4,"m":3,"o":5,"p":1,"q":1,"r":2, "s":1,"t":1,"u":1,"y":1}]}--->{"a":6,c":2,"d":2,"e ":3,}

标签: java json parsing


【解决方案1】:

首先你需要修复这个catch(Exception e) {}。如果您隐藏或不做任何异常的事情,那么您将不知道发生了什么以及为什么。此外,您只在bus == nullbus.length == 0 时才写入文件,对吗?然后您只将文件写入"C:\\Users\\andre\\Documents\\9SEMENESTRE\\FATIGA\\tarea\\Reporte.json",该路径是否正确?

编辑您的代码以包含一些调试并显示错误消息:

if (bus == null || bus.length == 0) {
    System.out.println("No hay elementos dentro de la carpeta actual");

    try (FileWriter file = new FileWriter("C:\\Users\\andre\\Documents\\9SEMENESTRE\\FATIGA\\tarea\\Reporte.json")){
        //Print a message to check if your code ever for here
        System.out.println("Attempting to write the file");
        file.write(jsd.toString());
        file.flush();
        //Print a success message
        System.out.println("The file was successfully written to");       
    }
    catch(Exception e) {
        //Print the error to the console
        e.printStackTrace();
    }
}

现在您将能够查看您的代码是否甚至可以写入文件,以及它失败的原因。

如果您仍然卡住,那么您需要更新您的问题以包含更多信息,包括调试详细信息。

【讨论】:

    【解决方案2】:

    首先,JSONObject jsonObject = new JSONObject(contents.trim()); 中的contents 是什么?我很确定您在上面引用了一个变量,您在某些时候更改了它的名称,因为我在这段代码的其他任何地方都看不到它。

    Iterator k = lang.iterator();
         
                    JSONObject jsonObject = new JSONObject(contents.trim());
                    Iterator<String> keys = jsonObject.keys();
    
                    while(keys.hasNext()) {
                        String key = keys.next();
                        if (jsonObject.get(key) instanceof JSONObject) {
                              JSONArray     
                        }
                    }
                    while (k.hasNext()) {
                        JSONObject innerObj = (JSONObject) k.next();
                        for (int i = 0; i < innerObj.size(); i++) {
                            System.out.println(i);
                        }
                        //System.out.println(innerObj.get(cadena.toString()));
                        
                    }
    

    您在这里的某个地方错过了对jsd 的呼叫。 我没有运行脚本,但只是阅读它,我看到的是您检查您要查找的文件是否存在,如果不存在,您使用已解析的数据创建文件对象jsd。但如果它确实存在,你永远不会那样做。您似乎正确打开文件,将其读入缓冲区,然后......您将该文件读回同一个文件?实际上,你似乎什么也没做。

    所以我认为这就是你的问题所在。

    有两点帮助:

    1. 就像 sorifiend 所暗示的那样,更好地使用您的catchs。为每一个添加某种 println 或消息,让您知道错误发生在哪里,它是什么类型,然后,是的,打印堆栈跟踪。
    2. 我建议您仔细阅读并撰写有关需要完成的工作以及正在完成的每个步骤的 cmets。倾向于过于明确的一面。甚至为每一行写一个注释。这样,当查看您的代码时,您会注意到您没有做一些重要的事情(例如写入文件)。

    【讨论】:

      猜你喜欢
      • 2011-04-04
      • 1970-01-01
      • 1970-01-01
      • 2013-02-18
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 1970-01-01
      • 2023-03-16
      相关资源
      最近更新 更多