I'm not sure if it can be done, but I'd like to parse a very simple JSON file to an array of Strings.
Example file:
["String1", "String2", "oneMoreString"]
So far I thought I'd use Scanner with a pattern to get my output, but failed to do this.
    ArrayList<String> strings = new ArrayList<String>();
    File f = new File("src/sample.txt");
    String pattern = "\\s*[\"\"]\\s*";
    try {
        InputStream is = new FileInputStream(f);
        Scanner s = new Scanner(is);
        s.useDelimiter(pattern);
        while (s.hasNext()){
            strings.add(s.next());
        }
        s.close();
        is.close();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
because the pattern is clearly wrong, since it considers ", " as it fits, but I'd like it wouldn't be included... :S
I also accept suggestions that may work to any other way this can be parsed. Maybe a JSON parser? but because the file is so simple I didn't consider it necessary.
It is better to use a JSON parser like Jackson Mapper to parse a JSON String.
But to if you have a simple String you can use a sample Regular expression to it quickly.
Try this out:
    String str = "[\"String1\", \"String2\", \"oneMoreString\"]";
    Pattern pattern = Pattern.compile("\"(.+?)\"");
    Matcher matcher = pattern.matcher(str);
    List<String> list = new ArrayList<String>();
    while (matcher.find()) {
        // System.out.println(matcher.group(1));.
        list.add(matcher.group(1));
    }
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With