Android JSONArray to ArrayList - java

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;
}

Related

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.

Android - Fetching Array with no name

I understand that what I'm fetching is already an array but still I'm not sure what to change here.
I have this which is returning data fine but I'm not sure what to do with the array to get the values into the map.
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://www.mywebsite.club/api/coffees");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("coffees");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("title", jsonobject.getString("title"));
map.put("brand", jsonobject.getString("brand"));
map.put("price", jsonobject.getInt("price"));
map.put("brandlogo", jsonobject.getString("brandlogo"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
From your response, I didn't find coffees attribute as array name, in your json response you have only array without attribute name. So you don't need to get json object from response, whatever your response string just get json array from that like,
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Array from the given URL address
jsonarray = new JSONArray(JSONfunctions.getJSONfromURL("http://www.mywebsite.club/api/coffees"));
try {
if(jsonarray != null)
{
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("title", jsonobject.getString("title"));
map.put("brand", jsonobject.getString("brand"));
map.put("price", jsonobject.getInt("price"));
map.put("brandlogo", jsonobject.getString("brandlogo"));
// Set the JSON Objects into the array
arraylist.add(map);
}
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}

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"}

How to get all values from JSONObject created with ArrayList ?

I am trying to get values from a json data with AsyncTask. I am getting only the last value and I don't understand why...
I tryed to parse with for each, while but I am doing something wrong :
Here is my code :
private class DecodeData extends AsyncTask<String, Void, String> {
protected ArrayList<HashMap<String, String>> decodedArray;
protected HashMap<String, String> decodedMap;
protected Iterator<String> it;
protected JSONArray m_Array;
protected JSONObject object;
protected String response;
protected String keys;
protected String value;
#SuppressWarnings("unchecked")
#Override
protected String doInBackground(String... params) {
response = params[0];
keys = "";
value = "";
object = null;
decodedArray = new ArrayList<HashMap<String, String>>();
try {
JSONArray arrayResp = new JSONArray(response);
for (int i = 0; i < arrayResp.length(); i++) {
decodedMap = new HashMap<String, String>();
it = arrayResp.getJSONObject(i).keys();
while (it.hasNext()) {
keys = (String)it.next();
value = Base64.DecodeStrToStr((String)arrayResp.getJSONObject(i).get(keys));
decodedMap.put("\""+keys+"\"", "\""+value+"\"");
object = new JSONObject(decodedMap.toString());
Log.i("DECODED MAP : ", object.toString());
m_Array = new JSONArray();
m_Array.put(object);
Log.i("M_ARRAY", ""+m_Array);
}
// decodedArray.add(decodedMap);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// array = new JSONArray(decodedArray);
return m_Array.toString();
}
I am using Volley to get response. After that, I create a JSONArray with this response and I get all keys/values from it. I put all of them in my Hashmap. But when i'm putting keys/values here : m_Array.put(object), it puts only the last value of my json data. Anybody has an idea of what I'm making wrong ?
Please create JSONArray before starting for loop..
m_Array = new JSONArray();
JSONArray arrayResp = new JSONArray(response);
for (int i = 0; i < arrayResp.length(); i++) { ....

Json / JsonArray to HashTable / List in Android

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

Categories

Resources