4

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.

4
  • 3
    You can have look at GSON parser code.google.com/p/google-gson Commented Dec 12, 2013 at 13:22
  • got in my path jackson.codehaus.org but it seems overkill to use a JSON parser... Commented Dec 12, 2013 at 13:24
  • 2
    @Daren, no, not overkill at all (to use Jackson/Gson). Introducing 10+ lines of regex code to process a simple JSON string is not the way to go (IMO). Commented Dec 12, 2013 at 13:29
  • ok, json it is, thnx for your opinion. Commented Dec 12, 2013 at 13:40

4 Answers 4

4

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));
    }
Sign up to request clarification or add additional context in comments.

4 Comments

matcher only axcepts strings, not input streams... can u try with scanner? for me this doesn't seem to work.. thnx!
You can use FileInputStream to read data read data from stream and then pass it to the matcher.
did it before you suggested it, it works. Thank you.
This would fall down if any of the strings contain escaped quote characters.
3

Seeing you have Jackson in your classpath, simply do:

ObjectMapper mapper = new ObjectMapper();
String[] array = mapper.readValue("[\"String1\", \"String2\", \"oneMoreString\"]", String[].class);
System.out.println(Arrays.toString(array));

which will print:

[String1, String2, oneMoreString]

1 Comment

I'll accept his solution (since the question has regexp) but use yours, Thank you. got my upvote.
1
//split by ,
String strings[] = s.split(",");
//remove [ from first string
strings[0] = strings[0].substring(1);
//remove ] from last string
String last = strings[strings.length - 1];
strings[strings.length - 1] = last.substring(0, last.length() - 1);

6 Comments

@Daren well, you wanted to avoid json parsers :)
Would be easier as s.substring(1,s.length()-1 (maybe 2?)).split(",")
Won't work if any of the JSON strings contain a comma.
@PhilKeeling yes, but from his question it looks like it wont
I was about to say that Phil - also it won't remove the quotes from around each string
|
-1

Instead of parsing it like above you can use any of the available Java json parsers

2 Comments

I know, any reason to do so except that i don't know reg-exp well enough? seems to me like overkill.
Consider it this way, you are parsing a JSON (JavaScript Object Notation) that must follow some rules, like be a key-value pair enclosed by { } etc. Usually libraries like GSON or Jackson (mentioned above) offer some validations in this aspect avoiding mal-formed json input, and usually (I have worked with both) they do quite well on performance; also using a json lib would provide you with other functionality to extend in the future if you need. If you are worried with performance you can always benchmark it by writing two methods and measure the time it takes to run, diff will be small.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.