Json / JsonArray to HashTable / List in Android - java

I created a method "Json to HashTable" and vice versa. I use HashTable because "Java" there are no associative arrays. My problem now is when there is an array in the json. This means from "Java" an array of HashTable :/ does not work at all but I think the solution is to use "List >" ...
I see this somewhat complicated. Any help? Is that hard or I complicate too?
Json example:
{"Config":[{"Name":"method1","Uses":"0","Event":["Start","Play"],"Action":{"Class":"Ads","Options":{"Class":"Webview","Url":"http:\/\/test.com\/action.php","Time":"10"}}},{"Name":"method2","Uses":"12","Event":["Loading"],"MaxTimes":"5","Options":{"Class":"Ads"}}]}
View in: http://json.parser.online.fr/
My code:
public Hashtable<?, ?> JSonDecode(String data) {
Hashtable<String, Object> htJS = new Hashtable<String, Object>();
try {
JSONObject objJS = new JSONObject(data);
Iterator<String> it = objJS.keys();
String key = null;
Object value = null;
while (it.hasNext()) {
key = it.next();
value = objJS.get(key);
if (value instanceof JSONObject) {
value = JSonObjectToHashtable(value.toString());
}
if (value instanceof JSONArray) {
value = JSonArrayToHashtable(value.toString());
}
htJS.put((String) key, value);
}
} catch (JSONException e) {
e.printStackTrace();
// No valid json
return null;
}
return htJS;
}
public Hashtable<?, ?> JSonObjectToHashtable(String data) {
Hashtable<String, Object> htJS = new Hashtable<String, Object>();
JSONObject objJS;
try {
objJS = new JSONObject(data);
Iterator<String> it = objJS.keys();
String key = null;
Object value = null;
while (it.hasNext()) {
key = it.next();
value = objJS.get(key);
if (value instanceof JSONObject) {
value = JSonObjectToHashtable(value.toString());
}
htJS.put((String) key, value);
}
} catch (JSONException e) {
e.printStackTrace();
}
return htJS;
}
public List<Map<String, Object>> JSonArrayToHashtable(String data) {
List<Map<String, Object>> listMap = new ArrayList<Map<String,Object>>();
Map<String,Object> entry = new HashMap<String,Object>();
JSONArray objJSA;
try {
objJSA = new JSONArray(data);
for (int i = 0; i < objJSA.length(); i++) {
JSONObject objJS = objJSA.getJSONObject(i);
Iterator<String> it = objJS.keys();
String key = null;
Object value = null;
while (it.hasNext()) {
key = it.next();
value = objJS.get(key);
if (value instanceof JSONObject) {
value = JSonObjectToHashtable(value.toString());
}
entry.put((String) key, value);
}
listMap.add(entry);
entry = new HashMap<String,Object>();
}
} catch (JSONException e) {
e.printStackTrace();
}
return listMap;
}

Map (Hashtable) API is similar to JSONObject API. There is really no need to convert JSONObject to Map unless your application uses Maps consistently.
If you need to convert JSONObject to Map, the Map can be of type Map<String, Object>, where Object can be one of the following types:
String
Primitive (Integer, Float, etc)
Map
Collection (Array, List, etc) of the tree types mentioned above

Related

Java:JSON to map using GSON

I have a string like this
{"key0":"value0","key1":"value1","key0":"value3"}
I want to store it in a map and the desired result is {"key0":"value3","key1":"value1"}
Using org.json.JsonObject: I passed the string to the constructor and Duplicate key exception is thrown
Using GSON: Same exception when I tried through new Gson.fromJson(string,Type)
Using Jackson: It does work
Is there a workaround to achieve the same using JSONObject and Gson
Interestingly if you first cast that json to an Object and then to a Map<String,String> your desired result happens:
String json = "{\"key0\":\"value0\",\"key1\":\"value1\",\"key0\":\"value3\"}";
Gson gson = new Gson();
Object obj = gson.fromJson(json, Object.class);
try {
Map<String,String> map = (Map<String, String>)obj;
// Outputs...
// key0=value3
// key1=value1
for (Map.Entry<String,String> entry : map.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
} catch (ClassCastException e) {
e.printStackTrace();
}
GSON uses MapTypeAdapterFactory to deserialioze map. Below is a short excerpt of its source code where a new entry is put in a map:
V replaced = map.put(key, value);
if (replaced != null) {
throw new JsonSyntaxException("duplicate key: " + key);
}
Knowing that there is at least one way to bypass this strict behavior: create your own map that overrides the method put(..) to return always null, like:
public class DuploMap extends HashMap<String, String>{
#Override
public String put(String key, String value) {
super.put(key, value);
return null;
}
}
then deserailizing to it like:
gson.fromJson(JSON, DuploMap.class);
will not throw that exception.
You can use GSON's JsonReader if you do not mind the manual effort.
On the plus side:
faster (no reflection, no casts)
fully under your control
--
String json = "{"key0":"value0","key1":"value1","key0":"value3"}";
JsonReader jsonReader = new JsonReader(new StringReader(json));
HashMap<String,String> map = new HashMap<String, String>()
String currKey;
try {
while(jsonReader.hasNext()){
JsonToken nextToken = jsonReader.peek();
if(JsonToken.NAME.equals(nextToken)){
currKey = jsonReader.nextName();
}
if(JsonToken.STRING.equals(nextToken)){
map.put(currKey, jsonReader.nextString())
}
}
} catch (IOException e) {
e.printStackTrace();
}

How to filter the values from the JsonObject in Android?

> {"-Kopv2EYUt7EeisRiiCz":{"deviceName":"LYF","fileUploadDate":"07\/12\/2017 2:00:57 PM"},
"-KopvA-cTtzgzSbsKTrw":{"deviceName":"LYF","fileUploadDate":"07\/12\/2017 2:01:29 PM",}}
How to parse all the "fileUploadDates" from the JsonObject ?
fileUploadDate = 07\/12\/2017 2:00:57 PM
fileUploadDate = "07\/12\/2017 2:01:29 PM
Use GSON library
public void parseJson(String json){
Gson gson = new Gson();
Type stringStringMap = new TypeToken<Map<String, Map<String,String>>>(){}.getType();
Map<String,Map<String,String>> map = gson.fromJson(json, stringStringMap);
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
Map<String,String> innerMap = (Map<String,String>)pair.getValue();
getInnerMapDetail(innerMap);
it.remove(); // avoids a ConcurrentModificationException
}
}
public void getInnerMapDetail(Map<String,String> innerMap)
{
String fileUploadDate = innerMap.get("fileUploadDate"); // you will get here
}
}
Try this for your Response to Parse
May Help you
try{
JSONObject jsonObject = new JSONObject(response);
List<String> keyList = getAllKeys(jsonObject);
for(String key : keyList){
JSONObject innerObject = jsonObject.getJSONObject(key);
String deviceName = innerObject.getString("deviceName");
String fileUploadDate = innerObject.getString("fileUploadDate");
System.out.println(deviceName +"--"+ fileUploadDate);
}
}catch(Exception e){
e.printStackTrace();
}
This method will return keys
private List<String> getAllKeys(JSONObject jsonObject) throws JSONException{
List<String> keys = new ArrayList<String>();
Iterator<?> iterator = jsonObject.keys();
while( iterator.hasNext() ) {
String key = (String)iterator.next();
keys.add(key);
}
return keys;
}
First you need to parse json objects and store in to String,like that
String fileUploadDate;
JSONObject -Kopv2EYUt7EeisRiiCz = new JSONObject;
fileUploadDate= sys.getString("fileUploadDate");
After you change string like that
String newfileUploadDate = string.replace("\", "");
you defiantly come to output.

JSON PII data masking in Java

I would like to mask certain elements of JSON and print to logs. Masking can be either by substituting by dummy data or removing the key pair .Is there a utility to do the masking in Java ?
E.g.,
given JSON:
{
"key1":"value1",
"key2":"value2",
"key3":"value3",
}
mask key 2 alone and print JSON:
{
"key1":"value1",
"key2":"xxxxxx",
"key3":"value3",
}
or
{
"key1":"value1",
"key3":"value3",
}
input will be JSON object or array type in string format. Here the maskable keys only static otherwise input string will dynamic.
public final class MaskPIData {
/**
* Mask able keywords mentioned here. It should be in LOWER CASE.
*/
private static final Set<String> MASKABLE_KEYS = new HashSet<>(Arrays.asList(
"email",
"emails",
"phone",
"pin",
"password",
"phonenumber",
"moneys"));
private static final String MASKING_VALUE = "****";
private static final ObjectMapper OBJECTMAPPER = new ObjectMapper();
private MaskPIData() {
super();
}
private static boolean isValidSet(Set<String> set) {
return set != null && !set.isEmpty();
}
private static boolean isKnownPrimitiveWrapperModel(Object obj) {
return obj == null || obj instanceof String || obj instanceof Integer || obj instanceof Long
|| obj instanceof Double;
}
#SuppressWarnings("unchecked")
private static JSONObject maskingForJsonObject(Set<String> maskableKeys, JSONObject input) {
if (!isValidSet(maskableKeys) || input == null) {
return input;
}
Map<String, Object> inputMap = (Map<String, Object>) input;
Map<String, Object> caseInsensitiveInputMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
caseInsensitiveInputMap.putAll(inputMap);
for (Map.Entry<String, Object> entryPair : caseInsensitiveInputMap.entrySet()) {
if (entryPair.getValue() instanceof JSONArray) {
JSONArray jsonArr = (JSONArray) caseInsensitiveInputMap.get(entryPair.getKey());
maskingForArray(maskableKeys, entryPair.getKey(), jsonArr);
caseInsensitiveInputMap.put(entryPair.getKey(), jsonArr);
} else if (entryPair.getValue() instanceof JSONObject) {
JSONObject jsonObj = (JSONObject) caseInsensitiveInputMap.get(entryPair.getKey());
caseInsensitiveInputMap.put(entryPair.getKey(), maskingForJsonObject(maskableKeys, jsonObj));
} else if (entryPair.getKey() != null && maskableKeys.contains(entryPair.getKey().toLowerCase())) {
caseInsensitiveInputMap.put(entryPair.getKey(), MASKING_VALUE);
}
}
return OBJECTMAPPER.convertValue(caseInsensitiveInputMap, JSONObject.class);
}
#SuppressWarnings("unchecked")
private static JSONArray maskingForArray(Set<String> maskableKeys, String key,
JSONArray jsonArr) {
JSONArray toRet = jsonArr;
for (int idx = 0; idx < toRet.size(); idx++) {
Object obj = toRet.get(idx);
if (isKnownPrimitiveWrapperModel(obj)) {
if (key != null && maskableKeys.contains(key.toLowerCase())) {
toRet.remove(idx);
toRet.add(idx, MASKING_VALUE);
}
} else {
JSONObject jsonObjFromArray = (JSONObject) toRet.get(idx);
JSONObject maskedJsonObj = maskingForJsonObject(maskableKeys, jsonObjFromArray);
toRet.remove(idx);
toRet.add(idx, maskedJsonObj);
}
}
return toRet;
}
public static String doMask(String input) {
String maskedData = input;
if (maskedData != null && !maskedData.trim().isEmpty()) {
try {
if (new JSONParser().parse(maskedData) instanceof JSONObject) {
JSONObject maskedOutput = maskingForJsonObject(MASKABLE_KEYS,
(JSONObject) new JSONParser().parse(maskedData));
maskedData = OBJECTMAPPER.writeValueAsString(maskedOutput);
} else if (new JSONParser().parse(maskedData) instanceof JSONArray) {
JSONArray maskedOutput = maskingForArray(MASKABLE_KEYS, null, (JSONArray) new JSONParser().parse(maskedData));
maskedData = OBJECTMAPPER.writeValueAsString(maskedOutput);
}
} catch (Exception e) {
// to do - Error while masking data
}
}
return maskedData;
}
public static void main(String args[]) {
String input = "{\"item\":{\"test\":\"test\",\"phone\":\"993244\",\"email\":\"mail#mail.com\"}}";
System.out.println(doMask(input));
}
You could use jackson to convert json to map, process map and convert map back to json.
For example:
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
public void mask() throws IOException {
String jsonString = "{\n" +
" \"key1\":\"value1\",\n" +
" \"key2\":\"value2\",\n" +
" \"key3\":\"value3\"\n" +
"}";
Map<String, Object> map;
// Convert json to map
ObjectMapper mapper = new ObjectMapper();
try {
TypeReference ref = new TypeReference<Map<String, Object>>() { };
map = mapper.readValue(jsonString, ref);
} catch (IOException e) {
System.out.print("cannot create Map from json" + e.getMessage());
throw e;
}
// Process map
if(map.containsKey("key2")) {
map.put("key2","xxxxxxxxx");
}
// Convert back map to json
String jsonResult = "";
try {
jsonResult = mapper.writeValueAsString(map);
} catch (IOException e) {
System.out.print("cannot create json from Map" + e.getMessage());
}
System.out.print(jsonResult);

Jackson ObjectMapper configuration - error JsonParseException: Unexpected character ('b' (code 98)):

I have generated JSON in the following format
[{"empNo":"2390","empName":"JAMES","projects":{"projectId":209,"projectName":"Z560"}}]
How do I configure ObjectMapper for the above?
I have declared ObjectMapper as
private static final ObjectMapper om = new ObjectMapper();
static {
om.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, false);
om.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
om.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS,
true);
om.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,
false);
om.getSerializationConfig().setSerializationInclusion
(JsonSerialize.Inclusion.NON_NULL);
}
However I am still getting the following error
com.sun.jersey.spi.container.ContainerResponse mapMappableContainerException
SEVERE: The exception contained within MappableContainerException could not
be mapped to a response, re-throwing to the HTTP container
org.codehaus.jackson.JsonParseException: Unexpected character ('b' (code 98)):
expected a valid value (number, String, array, object,
'true', 'false' or 'null') at [Source: java.io.StringReader#1fef0b44; line: 1,
column: 2]
Expected output is
{"empNo":"2390","empName":"JAMES","projectId":"209","projectName":"Z560"}
A bit lengthy, can be optimized. refer this for more.
public static void main(String[] args) throws IOException {
String originalJson = "{\"empNo\":\"2390\",\"empName\":\"JAMES\",\"projects\":{\"projectId\":209,\"projectName\":\"Z560\"}}";
try {
JSONObject jsonObject = new JSONObject(originalJson);
Map<String, Object> map = getMap(jsonObject);
System.out.println("My Old Map => " + map);
Map<String, Object> newMap = new HashMap<String, Object>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getKey().equals("projects")) {
Map<String, Object> projectMap = (Map<String, Object>) entry.getValue();
for (Map.Entry<String, Object> entry1 : projectMap.entrySet()) {
newMap.put(entry1.getKey(), entry1.getValue());
}
} else {
newMap.put(entry.getKey(), entry.getValue().toString());
}
}
JSONObject jsonObject1 = new JSONObject(newMap);
System.out.println("My New Map => " + newMap);
System.out.println("Expected Json String => " + jsonObject1.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static Map getMap(JSONObject object) {
Map<String, Object> map = new HashMap<String, Object>();
Object jsonObject = null;
String key = null;
Object value = null;
try {
Iterator<String> keys = object.keys();
while (keys.hasNext()) {
key = null;
value = null;
key = keys.next();
if (null != key && !object.isNull(key)) {
value = object.get(key);
}
if (value instanceof JSONObject) {
map.put(key, getMap((JSONObject) value));
continue;
}
if (value instanceof JSONArray) {
JSONArray array = ((JSONArray) value);
List list = new ArrayList();
for (int i = 0 ; i < array.length() ; i++) {
jsonObject = array.get(i);
if (jsonObject instanceof JSONObject) {
list.add(getMap((JSONObject) jsonObject));
} else {
list.add(jsonObject);
}
}
map.put(key, list);
continue;
}
map.put(key, value);
}
} catch (Exception e) {
System.out.println(e);
}
return map;
}
Output
My Old Map => {projects={projectId=209, projectName=Z560},
empName=JAMES, empNo=2390}
My New Map => {empName=JAMES, empNo=2390, projectId=209,
projectName=Z560}
Expected Json String =>
{"empName":"JAMES","empNo":"2390","projectId":209,"projectName":"Z560"}

Android JSONArray to ArrayList

I am trying to parse a JSONArray into and ArrayList in my android app. The PHP script correctly retuns the expected results, however the Java fails with a null pointer exception at resultsList.add(map)
public void agencySearch(String tsearch) {
// Setting the URL for the Search by Town
String url_search_agency = "http://www.infinitycodeservices.com/get_agency_by_city.php";
// Building parameters for the search
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("City", tsearch));
// Getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url_search_agency, params);
for (int i = 0; i < json.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
try {
JSONObject c = (JSONObject) json.get(i);
//Fill map
Iterator iter = c.keys();
while(iter.hasNext()) {
String currentKey = (String) iter.next();
map.put(currentKey, c.getString(currentKey));
}
resultsList.add(map);
}
catch (JSONException e) {
e.printStackTrace();
}
};
MainActivity.setResultsList(resultsList);
}
try like this may help you,
public void agencySearch(String tsearch) {
// Setting the URL for the Search by Town
String url_search_agency = "http://www.infinitycodeservices.com/get_agency_by_city.php";
// Building parameters for the search
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("City", tsearch));
// Getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url_search_agency, params);
ArrayList<HashMap<String, String>> resultsList = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < json.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
try {
JSONObject c = json.getJSONObject(position);
//Fill map
Iterator<String> iter = c.keys();
while(iter.hasNext()) {
String currentKey = it.next();
map.put(currentKey, c.getString(currentKey));
}
resultsList.add(map);
}
catch (JSONException e) {
e.printStackTrace();
}
};
MainActivity.setResultsList(resultsList);
}
Use custom method which convert your JSONArray to List instead of iterate and build List.
How to call :
try {
ArrayList<HashMap<String,String>> list = (ArrayList<HashMap<String,String>>) toList(json);
} catch (JSONException e) {
e.printStackTrace();
}
Convert json array to List :
private List toList(JSONArray array) throws JSONException {
List list = new ArrayList();
int size = array.length();
for (int i = 0; i < size; i++) {
list.add(fromJson(array.get(i)));
}
return list;
}
Convert json to Object :
private Object fromJson(Object json) throws JSONException {
if (json == JSONObject.NULL) {
return null;
} else if (json instanceof JSONObject) {
return jsonToMap((JSONObject) json);
} else if (json instanceof JSONArray) {
return toList((JSONArray) json);
} else {
return json;
}
}
Convert json to map :
public Map<String, String> jsonToMap(JSONObject object) throws JSONException {
Map<String, String> map = new HashMap();
Iterator keys = object.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
map.put(key, fromJson(object.get(key)).toString());
}
return map;
}

Categories

Resources