I want to pass this JSON String to a Java class through command line arguments.
{"body": "We should definitely meet up, man", "startDate": "2014-05-29 11:00:00", "endDate": "2014-05-29 12:00:00", "location": "Boca Raton", "subject": "This is the subject of our meeting."}
However, at every space, the String gets split up. So args[0] is
{"body":
args[1] is
"We
etc.
I want args[0] to just be
{"body": "We should definitely meet up, man", "startDate": "2014-05-29 11:00:00", "endDate": "2014-05-29 12:00:00", "location": "Boca Raton", "subject": "This is the subject of our meeting."}
I tried using double quotes, but since there are quotes in the JSON string it didn't work.
How can I do this? Thanks so much!
Here is a better solution:
This isn't a Java issue: it's a shell issue. So the answer depends on what shell you're using.
If you're on a UNIX-y shell, try putting the JSON within single quotes. For instance: java my.MainClass '{ "key1": "value1" }'. That'll probably work on Windows, too ... I'm not sure.
If you have a ' in your JSON, things get complicated. If your shell is Bash, one option is to replace every ' with '\''.
But where is the JSON coming from? If you're actually invoking this Java program from within another program, you can skip the shell altogether. Python's subprocess.call, Ruby's IO.popen, Bash's "$@" and Java's ProcessBuilder all accept an array of command-line arguments instead of a single-string command. Alternatively, logic like Ruby's Shellwords exists for just about any programming language and quotes command-line parameters so the shell parses them into exactly the bytes you specify.
Another alternative: you can pipe the JSON to your program. Invoke it like this (on UNIX):
cat | java my.MainClass
{
"you can just type": "this stuff",
"and it will eventually get picked up by": "Java"
}
[Ctrl-d (UNIX) or Ctrl-z (Windows)]
And read it in Java as discussed at Read/convert an InputStream to a String -- using System.in as the InputStream.
You need to escape the double-quote characters and surround the entire String with normal double-quotes:
java Test "{\"body\": \"We should definitely meet up, man\", \"startDate\": \"2014-05-29 11:00:00\", \"endDate\": \"2014-05-29 12:00:00\", \"location\": \"Boca Raton\", \"subject\": \"This is the subject of our meeting.\"}"
This is a Windows example.
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