Skip to content

Instantly share code, notes, and snippets.

@Zelakolase
Created February 15, 2022 12:35
Show Gist options
  • Save Zelakolase/afe1b8b0d6e8bde43e0d87dac60a235c to your computer and use it in GitHub Desktop.
Save Zelakolase/afe1b8b0d6e8bde43e0d87dac60a235c to your computer and use it in GitHub Desktop.
JSON to HM and vice versa
import java.util.HashMap;
import java.util.Map;
public class JSON {
public static HashMap<String, String> QHM(String Q) {
HashMap<String, String> HM = new HashMap<String, String>();
Q = Q.replaceFirst("\\{", "").substring(0, Q.length()-2); // {“user”:”x”,”pass”:”y”} -> “user”:”x”,”pass”:”y”
String[] pairs = Q.split(","); // ["user":"x" , "pass":"y"]
for(int i = 0;i < pairs.length;i++) {
String[] pair = pairs[i].split(":"); // "user" , "x"
HM.put(pair[0].replaceFirst("\"", "").substring(0, pair[0].length()-2),
pair[1].replaceFirst("\"", "").substring(0, pair[1].length()-2));
}
return HM;
}
public static String HMQ(HashMap<String, String> HM) {
String Q = "{";
int iter = 0;
for (Map.Entry<String, String> entry : HM.entrySet()) {
String E = "\""+entry.getKey()+"\":"+"\""+entry.getValue()+"\"";
iter++;
if(! (iter+1 > HM.size())) {
E += ",";
}
Q += E;
}
Q += "}";
return Q;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment