简体   繁体   English

使用Scanner接受Java控制台应用程序中用户格式化的Json(多行)输入(不读取所有行)

[英]Accepting formatted Json (multi-line) input from user in a Java console app with Scanner (all lines not being read)

I have a scenario where I need to take formatted Json (multi-line) as an input and do something with it. 我有一种情况,我需要将格式化的Json(多行)作为输入并对其进行处理。 I figured doing it in a simple console app would be good since it is just a tool I am creating and want it to be able to be ran locally. 我认为在一个简单的控制台应用程序中进行操作会很好,因为它只是我正在创建的工具,并且希望能够在本地运行。 If I should be reading the Json from a file instead please let me know. 如果我应该从文件中读取Json,请告诉我。

The plan is to have the user paste something like this into a console application and then type "exit". 计划是让用户将类似这样的内容粘贴到控制台应用程序中,然后键入“ exit”。

    {
       "section1":{
          "line1":0.3456,
          "line2":{
             "line3":45345,
             "line4":67567
          },
          "section2":{
             "line6":867867,
             "line7":0.16767
          },
          "section3":{
             "line9":9977,
             "line10":0.76867
          },
          "array1":[
             {
                "ghjf":"1111",
                "ggeeaaa":678769,
                "ghj":0.6799789
             }
          ]
       }
    }
exit

A couple of things are happening: 有几件事正在发生:
1. The first { is not being recognized so I need to manually insert it. 1.第一个{无法识别,因此我需要手动将其插入。
2. Several lines are not being read... ie "line1" is getting skipped and many more. 2.几行未读...即“ line1”被跳过,还有更多行。

Here is my code: 这是我的代码:

System.out.println("Enter a valid JSON string: ");

Scanner scanner = new Scanner(System.in);

StringBuilder sb = new StringBuilder();

while (!scanner.nextLine().equals("exit")) {
    sb.append(scanner.nextLine());
}

sb.insert(0, "{");

String formattedJson = sb.toString()
        .replaceAll("\\t","").replaceAll("\\s", "");


 // Do something with formattedJson further in code...

You are calling scanner.nextLine() twice, but only use the value once. 您两次调用scanner.nextLine(),但仅使用一次该值。

Try declaring it as a variable and only calling nextLine() once: 尝试将其声明为变量,并且只调用一次nextLine():

Scanner scanner = new Scanner(System.in);

StringBuilder sb = new StringBuilder();

String line;
while (!(line = scanner.nextLine()).equals("exit")) {
    sb.append(line);
}

As a result, you probably won't need (should remove) this: 结果,您可能不需要(应该删除):

sb.insert(0, "{");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM