Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Write the provided data to JSON, e.g.
- *
- * <pre>
- * {
- * "OuterKey_1": {
- * "SubKey_1_1": 1,
- * "SubKey_1_2": 2
- * },
- * "OuterKey_2": {
- * "SubKey_2_1": 1,
- * "SubKey_2_2": 2,
- * "SubKey_2_3": 3
- * }
- * }
- * </pre>
- * @param data The data to print
- * @param os The stream to which the JSON will be written
- * @throws IOException
- */
- public static void writeToJSON(Hashtable<String,Hashtable<String,Integer>> data, OutputStream os)
- throws IOException {
- Escaper esc = new Escaper(false);
- PrintWriter pw = new PrintWriter(os,true);
- pw.println("{");
- if(data == null){
- pw.println("}");
- return;
- }
- Enumeration<String> outerKeys = data.keys();
- while(outerKeys.hasMoreElements()) {
- String outerKey = outerKeys.nextElement();
- // "outerKey": {
- pw.println(String.format("\t\"%s\": { ", esc.escapeJsonString(outerKey)));
- Hashtable<String,Integer> innerData = data.get(outerKey);
- Enumeration<String> innerKeys = innerData.keys();
- while(innerKeys.hasMoreElements()){
- String innerKey = innerKeys.nextElement();
- // "innerKey": innerVal
- pw.print(String.format("\t\t\"%s\": %d ", esc.escapeJsonString(innerKey), innerData.get(innerKey)));
- pw.println(innerKeys.hasMoreElements() ? ",":"");
- }
- pw.print("\t}");
- pw.println(outerKeys.hasMoreElements() ? ",":"");
- }
- pw.println("}");
- }
Add Comment
Please, Sign In to add comment