Facebook Interview Question
SDE1sCountry: United States
public static void jsonToMap(String t) throws JSONException {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jObject = new JSONObject(t);
Iterator<?> keys = jObject.keys();
while( keys.hasNext() ){
String key = (String)keys.next();
String value = jObject.getString(key);
map.put(key, value);
}
System.out.println("json : "+jObject);
System.out.println("map : "+map);
}
Or if we don't want to use JSONObject library, we can write in the following way.
String tempJson = "{\"incomePhone\":\"213121122\",\"clientId\":\"1001\",\"clientAccountManager\":\"Gestor de Conta 1\",\"clientRetailBranch\":\"100\",\"phoneAccountManager\":\"7800100\"}";
System.out.println(tempJson);
String[] parts = tempJson.split(",");
HashMap<String,String> jsonHash = new HashMap<String,String>();
for(int i=0;i<parts.length;i++){
parts[i] = parts[i].replace("\"", "");
parts[i] = parts[i].replace("{", "");
parts[i] = parts[i].replace("}", "");
String[] subparts = parts[i].split(":");
jsonHash.put(subparts[0],subparts[1]);
}
Allowed to use language's json parser or have to manually create our own?
- tnutty2k8 August 03, 2017