ArrayList of HashMap elements to Array - java

How can I get an array of elements in a ArrayList of HashMaps? I have an HashMap with url key on it. The value is a url address. Several HashMaps are stored in a ArrayList. What I want is an array with all url strings. I'm not happy with the solution I found because I think it could be extracted from ArrayList with some manipulation.
// Hashmap for ListView
ArrayList<HashMap<String, String>> itemsList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
jParser.execute(url);
try {
JSONObject json = jParser.get();
items = json.getJSONArray(TAG_ITEMS);
//This is the solution that I want to optimize
urls = new String[items.length()];
// looping through All items
for(int i = 0; i < items.length(); i++){
JSONObject c = items.getJSONObject(i);
// Storing each json item in variable
String title = c.getString(TAG_TITLE);
String description = c.getString(TAG_DESCRIPTION);
String author = c.getString(TAG_AUTHOR);
// Media is another JSONObject
JSONObject m = c.getJSONObject(TAG_MEDIA);
String url = m.getString(TAG_URL);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_TITLE, title);
map.put(TAG_DESCRIPTION, description);
map.put(TAG_AUTHOR, author);
map.put(TAG_URL, url);
// Solution
urls[i] = url;
// adding HashList to ArrayList
itemsList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}

From what I can deduce from your question, it sounds like you're trying to do the following
// Assuming previously declared and instantiated urls ArrayList with populated values in the nested HashMaps.
ArrayList<HashMap<String, String>> urls;
// Create a new List using HashMap.values from urls.
List<String> urlList = new ArrayList<String>(urls.get(index).values());
urls.get(index).values() will return a Collection view of the values contained in the HashMap at the specified ArrayList index, which will be used to instantiate and populate a new ArrayList.
If you want to obtain all of the values within each of the nested HashMaps or urls, you can do so in a similar manner, but you will need to iterate through the entire urls ArrayList
for (HashMap<String, String> urlValues : urls) {
urlList.addAll(urlValues.values());
}
P.S. Forgive my bad variable names!

It looks like you are building a table. If you can add the Google Guava Library, you could just use the following:
Table<Integer, String, String> Table = HashedBasedTable.create()
See the JavaDoc:
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Table.html

Related

How to dynamically loop a JSON file using Thymeleaf in Spring boot

I have a requirement wherein I need to iterate over a List of Maps i.e. List<Map<String, Object>> grab the data from the list, and map it to a JSON file. Now the challenge is that I need to loop the data dynamically in the JSON file. Well, I do know how to map a single set of data to a JSON file using Thymeleaf but I'm not sure how to dynamically loop a JSON file using Thymeleaf.
The following thing is what I'm aware of -
I have a java class with a method that has the following code that will map the data from a HashMap to the JSON file.
public JSONObject response(){
Map<String, Object> map = new HashMap<>();
Context context = new Context();
String responsePayload = null;
JSONObject jsonObject = null;
data.put("name", "Wayne Rooney")
data.put("profession", "Footballer")
context.setVariable("data", data);
responsePayload = templateEngine.process("resource/payload", context);
jsonObject = new JSONObject(responsePayload);
}
This is how the payload.json file looks
{
"name": "[(${data['name']})]",
"profession": "[(${data['profession']})]"
}
So, my code works smoothly when only a single instance of HashMap data is mapped to the JSON file, but my next requirement is how do I loop a List of Maps i.e. List<Map<String, Object>> and map the data in my json file?
For e.g. Consider now I've a List<Map<String, Object>> instead of Map<String, Object>
public JSONObject response(){
List<Map<String, Object>> listOfMap = new ArrayList<>();
Map<String, Object> data1 = new HashMap<>();
Map<String, Object> data2 = new HashMap<>();
Map<String, Object> data3 = new HashMap<>();
Context context = new Context();
String responsePayload = null;
JSONObject jsonObject = null;
data1.put("name", "Wayne Rooney")
data1.put("profession", "Footballer")
data2.put("name", "Cristiano Ronaldo")
data2.put("profession", "Footballer")
data3.put("name", "Sir Alex Ferguson")
data3.put("profession", "Manager")
listOfMap.add(data1);
listOfMap.add(data2);
listOfMap.add(data3);
context.setVariable("data", listOfMap);
responsePayload = templateEngine.process("resource/payload", context);
jsonObject = new JSONObject(responsePayload);
return jsonObject;
}
So now how do I map this list of data to a JSON file? What changes do I need to make in the JSON file?
I appreciate it if someone helps here.
Thank you!

Need to display count of distinct locations associated with IP address using Hashmap

We're working on a project and one of the things we need done is to show how many different locations a mac address has shown up in. We're using RedisGraph to query the information and I've used a hashmap to get the data. My problem is that I'll have a mac address listed in the json response multiple times, 3 of the times with the same location and one of the times with a different location. I want to get a JSON response that shows that mac address with a location count of 2, so it only counts distinct locations. Any help is much appreciated and below is my code.
ResultSet resultSet = api.query(GET_COUNT_OF_LOCATIONS_FOR_DEVICE);
JSONArray finalResult = new JSONArray();
JSONArray jsonArray = new JSONArray();
try {
while (resultSet.hasNext()) {
JSONObject joined = new JSONObject();
Map<String, String> mac = new HashMap<String, String>();
Map<String, String> location = new HashMap<String, String>();
Map<String, String> location_count = new HashMap<String, String>();
Record record = resultSet.next();
mac.put("mac_address", record.getString("m.address"));
location.put("location", record.getString("l.lo"));
location_count.put("location_count", record.getString("l.lo"));
joined.put("mac_address", mac.values().stream().map(i -> i).collect(Collectors.toSet()));
joined.put("location", location.values().stream().map(i -> i).collect(Collectors.toSet()));
joined.put("location_count", location.values().stream().map(i -> i).collect(Collectors.toSet()).size());
jsonArray.put(joined);
}
} catch (Exception e) {
e.printStackTrace();
}
finalResult.put(jsonArray);
return finalResult;
}

Convert JSON String to Arraylist for Spinner

I got my JSON string from my server which contains this values:
{"server_response":[{"violation":"Driving with No Helmet"},{"violation":"Try"}]}
What I'm trying to do is convert this JSON string into String Array or Arraylist
with the values of Driving with no Helmet and Try and use it as options on an Autocomplete Textview. But I cant seem to convert them correctly. Any help or tips on what I should do? Currently I am getting the JSON String from another activity and passing it to the activity where it should be used using this:
String json_string2 = getIntent().getExtras().getString("json_data");
Anyone has time I'm willing to learn. :) Thanks
PS: Managed to get it working. #Suhafer's answer is perfect. Thanks to everyone for the warm help! :)
I think first, you need to parse the json to get the list of string that you want:
String json_string2 = getIntent().getExtras().getString("json_data");
List<String> lStringList = new ArrayList<>();
try {
JSONObject lJSONObject = new JSONObject(json_string2);
JSONArray lJSONArray = lJSONObject.getJSONArray("server_response");
for (int i = 0; i < lJSONArray.length(); i++)
{
lStringList.add(
lJSONArray.getJSONObject(i).getString("violation"));
}
}
catch(Exception e)
{
e.printStackTrace();
}
Then, you need to set that list to your adapter:
ArrayAdapter<String> yourListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, lStringList);
Next, implement the adapter to your AutoCompleteTextView.
lAutoCompleteTextView.setAdapter(lStringArrayAdapter);
Hope, that helps you.
Reading your comment I think you want this list to populate on an AutoCompleteTextView. I have written thoroughly what to do this will surely help If you follow these steps carefully.
First get the response and convert it to List<String> list = new ArrayList<>() format, Create a ArrayAdapter of this list by
yourListAdapter = new ArrayAdapter<String>(YourActivity.this,
android.R.layout.simple_list_item_1, list);
After this set your yourAutoCompleteTextBoxName.setAdapter(yourListAdapter);
In your Activity initialize this:
yourAutoCompleteTextBoxName.setOnEditorActionList(...){...}
also if you want your list to be clicked from AutoComplete TextView then do this:
yourAutoCompleteTextBoxName.setOnItemClickListener(...){...}
You can do this as below by using jettinson.jar
try {
String data = "{\"server_response\":[{\"violation\":\"Driving with No Helmet\"},{\"violation\":\"Try\"}]}";
JSONObject jsonObject = new JSONObject(data);
JSONArray temp = jsonObject.getJSONArray("server_response");
int length = temp.length();
if (length > 0) {
String[] recipients = new String[length];
for (int i = 0; i < length; i++) {
JSONObject nObject = new JSONObject(temp.getString(i));
recipients[i] = nObject.getString("violation");
}
}
} catch (JSONException ex) {
Logger.getLogger(JavaApplication2.class.getName()).log(Level.SEVERE, null, ex);
}
For getting your list of strings:
You can use Jackson's ObjectMapper class.
public class Data {
String violation;
...
}
List<Data> violations = objectMapper.readValue(json, new TypeReference<List<Data>>(){});
Below: "array" will have all the violations. (You will require some try / catch to surround with). Have a good day!
JSONObject json = new JSONObject(json_string2);
JSONArray violations = json.getJSONArray("server_response");
String[] array = new String[violations.length()];
for(int i = 0; i < violations.length(); i++) {
JSONObject violation = new JSONObject(violations.getString(i));
array[i] = violation.getString("violation");
}
You can use Gson library https://github.com/google/gson
Generate Plain Old Java Objects from JSON or JSON-Schema http://www.jsonschema2pojo.org/
YourJsonData jsonObject;
String json_string2 = getIntent().getExtras().getString("json_data");
Gson gson = new Gson();
jsonObject = gson.fromJson(json_string2, YourJsonData.class);
from jsonObject you can get your list i.e server_response array list.

How to store and retrive HashMap<Integer, boolean[]> hashMapB=new HashMap<Integer,boolean[]>() into shared preferences in android

I want to create Expandable List view for filter and i am storing check box status of every group into HashMap .but after apply filter first time and again going for the filter i am not able to retain state of check box.I want to store it into shared preference . can any one suggest how to do it.
Inserting Into Shared Pref,
HashMap<Integer, boolean[]> hashmapB = new Hashmap<>;
After Adding Values to Hashmap then convert it JSON
JSONObject jsonObject = new JSONObject(hashmapB);
String jsonString = jsonObject.toString();
SharedPreferences keyValues = getSharedPreferences("Your_Shared_Prefs"), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = keyValues.edit();
editor.putString("hashmapB_key",jsonString);
Retrieve From Pref,
String hashmapB_String = Sellerregistration_Pref.getString("hashmapB_key",
(new JSONObject()).toString());
String To Hashmap (Here You Might Get Problem I just did this based on assumption),
HashMap<Integer,boolean[]>hashmapB_Ret = new HashMap<>();
try {
JSONObject jsonObject = new JSONObject(hashmapB_String);
Iterator<String> keysItr = jsonObject.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
boolean[] values = (boolean[]) jsonObject.get(key);
hashmapB_Ret.put(Integer.valueOf(key), value);
}
} catch (JSONException e) {
e.printStackTrace();
}

Parsing json url

I am trying to create an image view from json url. I am getting the url using a for-loop in a string. I could not use that variable outside the for-loop. I tried constructing an arraylist inside the for-loop. This is what I am getting in the log.
Creating view...[[], [], [], [], [], [], [], [], [], []]
Here is my code.
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
// Log.v("url", "Creating view..." + json);
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_URL);
for (int i = 0; i < android.length(); i++) {
map = new ArrayList<HashMap<String, String>>();
JSONObject c = android.getJSONObject(i);
String name = c.getString(TAG_URL);
arraylist.add(map);
// Log.v("url", name);
}
Log.v("url", "Creating view..." + arraylist);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Here is the json:
http://www.json-generator.com/api/json/get/ciCLARKtKa?indent=4
When in doubt on how to create a POJO from a JSON, I'd recommend you to try this site:
http://www.jsonschema2pojo.org/
It outputs you a full java class that works for a given json type;
For most cases I'd recommend you to use this config (from the website above):
Source type: Json
Annotation style: None
And check ONLY use primitives.
Hope it helps !
hi do something as follows
JSONObject primaryObject = new JSONObject(//yours json string);
JSONArray primaryArray = primaryObject.getJSONArray("worldpopulation");
for (int i = 0; i < primaryArray.length(); i++) {
JSONObject another = primaryArray.getJSONObject(i);
String country = another.getString("country");
String flag = another.getString("flag");
int rank = another.getInt("rank");
String population = another.getString("population");
HashMap<String, String> map = new HashMap<String, String>();
map.put("flag", flag);
arraylist.add(i, map);
}
I think you missed put the values into MAP.
Try use like this
for (int i = 0; i < android.length(); i++) {
JSONObject c = android.getJSONObject(i);
// Storing each json item in variable
String flag = c.getString("flag");
HashMap<String, String> map = new HashMap<String, String>();
map.put("flag", flag);
arraylist.add(i, map);
}

Categories

Resources