Studyon Minte9.com
Java SE




Json



In order to use a third-party library in Java (like JSON-lib in your case), the library must be present during 
compilation and during execution (runtime) of your program. This is done by downloading the .jar file and telling 
Java where to find it. Java uses the concept of classpath

1) Put the jar file on extensions folder
	json-simple-1.1.1.jar
	C:Program FilesJavajdk1.6.0_37jrelibext

Sometimes you need to:

2) Environmet Variables
	CLASSPATH
	C:Program FilesJavajdk1.6.0_37jrelibextjson-simple-1.1.1.jar

3) Example

package testexample; import java.util.Map; import org.json.simple.JSONValue; public class Test { public static void main (String[] args) { //String ss = "{"message_info":{"message_type":"trade_feed","timestamp":"1"},"error":"0"}"; //System.out.println(ss); // use key/values with double quotes escaping String s = "{message_info={message_type=trade_feed|timestamp=1},error=0}"; s = s.replaceAll("([^={}|]+)=", ""$1"="); // add quotes to keys s = s.replaceAll("=([^={}|]+)", "="$1""); // add quotes to values s = s.replace("|", ",").replace("=", ":"); System.out.println(s); // Outputs: {"message_info":{"message_type":"trade_feed","timestamp":"1"}",error":"0"} Object obj = JSONValue.parse(s); Map mp = (Map)obj; String message_type = ((Map)mp.get("message_info")).get("message_type").toString(); System.out.println(message_type); // Output: instrument_get } }
  4) Parse Key/Value Object obj = JSONValue.parse(s); //System.out.println(obj); Parser p = new Parser(obj); HashMap map = (HashMap)obj; Set<Map.Entry<String, String>> set = map.entrySet(); for(Map.Entry<String, String> x:set) { System.out.println(x.getKey() + x.getValue()); } 5) Get value by key String s = {"message_info":{"message_type":"trade_feed","timestamp":"1"},"error":"0"}; Object obj = JSONValue.parse(s); Map mp = (Map)obj; String message_type = ((Map)mp.get("reply_to")).get("message_type").toString(); System.out.println(message_type); // Output: instrument_get // Map parameters = (Map)mp.get("parameters"); // String market = ((Map)parameters.get("basecontract")).get("market").toString(); // System.out.println(market); // ROR FIX42


http://code.google.com/p/json-simple