Reputation: 3677
The following code is in PHP. I want to do the same in Java. Please tell me how do I generate this type of array or collection in Java. I need this to response to JSON autocomplete.
<?php
$q = strtolower($_GET["q"]);
if (!$q) return;
$items = array(
"Peter Pan"=>"[email protected]",
"Molly"=>"[email protected]",
"Forneria Marconi"=>"[email protected]",
"Master Sync"=>"[email protected]",
"Dr. Tech de Log"=>"[email protected]",
"Don Corleone"=>"[email protected]",
"Mc Chick"=>"[email protected]",
"Donnie Darko"=>"[email protected]",
"Quake The Net"=>"[email protected]",
"Dr. Write"=>"[email protected]"
);
$result = array();
foreach ($items as $key=>$value) {
if (strpos(strtolower($key), $q) !== false) {
array_push($result, array(
"name" => $key,
"to" => $value
));
}
}
echo json_encode($result);
?>
I want java version of this PHP code because this code is returning in JSON format. In
{name=>"Peter Pan",
to=>"[email protected]";
.....}
As you see this:-
array_push($result, array(
"name" => $key,
"to" => $value
));
Which can be handled by this jQuery code:-
$('#inputItem').autocomplete('<c:url value="/json/itemautocomplete.do" />', {
multiple: true,
mustMatch: true,
autoFill: true,
highlight: false,
scroll: true,
dataType: "json",
parse: function(data){
var array = new Array();
for(var i = 0; i<data.length; i++){
array[array.length] = {data: data[i], value: data[i].name, result: data[i].name};
}
return array;
}
});
This plugin is available on this url
I know how to handle JSON data by using JSONArray
in $.getJSON
jQuery method. But that thing is not working in this case. I think I need to format my data as I described above in this answer so that this jQuery autocomplete plugin can understand the data. Please tell me how can I get this...
Upvotes: 0
Views: 1299
Reputation: 3677
Thanks for ur support.
I have handled the data by using this code:- In Servlet:-
LinkedList arr = new LinkedList();
arr.add("Peter Pan <[email protected]>");
arr.add("Molly <[email protected]>");
arr.add("Forneria Marconi <[email protected]>");
Iterator iter = arr.iterator();
while(iter.hasNext()){
out.println(iter.next());
}
In JQuery:-
function itemAutocomplete(){
$('#inputItem').autocomplete('<c:url value="/json/itemautocomplete.do?mi=' + $('#sltMainItem').val() + '&si=' + $('#sltSubItem').val() + '" />', {
json: true
});
}
Thanks for being here for me Shams
Upvotes: 0
Reputation: 81124
In Java, you would use a Map<String, String>
:
Map<String, String> items = new HashMap<String, String>();
items.put("Peter Pan", "[email protected]");
String petersAddress = items.get("Peter Pan");
You can iterate through the keyset:
for ( String key : items.keySet() ) {
if ( key.toLowerCase().startsWith(input) ) {
//add to list of potential matches
}
}
Upvotes: 1