Pages

Monday, January 20, 2014

Compiling and creating jar of JSON Java

This is mostly going to be a "note to self" since I'm going to cover some very basic stuff such as:

  1. get code from github
  2. compile Java files into .class files
  3. create jar file
  4. import into Eclipse
I happened to need a JSON parser in a  Java project and chose the reference implementation from json.org site.

$ # 1. clone Git repository (it's like svn checkout)
$ git clone https://github.com/douglascrockford/JSON-java
$ 
$ # 2. change directory to the downloaded JSON-java directory
$ cd JSON-java/
$ 
$ # 3. add all the .java files in the current and subdirectories into a file called sources.txt
$ find . -type f -name "*.java" > sources.txt
$ 
$ # 4. create a directory to place the compiled .class files called build
$ mkdir build
$ 
$ # 5. tell Java compiler to read the files from sources.txt and place the compiled files in the build directory
$ javac @sources.txt -d build
$ 
$ # 6. change directory to the build directory
$ cd build/
$ 
$ # 7. create jar file named JSON-java.jar including all (*) files in the current and child directories
$ jar -cf JSON-java.jar *
$ 
$ # 8. copy jar file to Eclipse's WEB-INF/lib/ directory
$ cp JSON-java.jar /path/to/eclipse/workspace/project_name/war/WEB-INF/lib/

After the jar file was copied to /war/WEB-INF/lib/ directory of the Eclipse project, open Eclipse and "include" it:
  1. from Eclipse's menu, open Project > Properties
  2. on the left pane, choose Java Build Path
  3. select Libraries tab
  4. click on Add External JARs button
  5. browse to the /war/WEB-INF/lib/ directory of your project and select JSON-java.jar
  6. click OK to close dialog
  7. in any .java file, in the import statements, try to add the following import:
import org.json.*

If it doesn't become red it means everything is fine. If there's anything wrong, check each step, especially the generation of .class files.

Cheers! 



No comments:

Post a Comment

Your feedback is very welcome! No spam please.