Reputation: 2785
I am parsing a JSON
in my activity to display both text and images in a gridView
.However i would like to try to add search functionality on this JSON
and display the results on the activity.
For example consider a JSON
script on an online server like this:
[
{
"title": "Ongata Rongai",
"image": "http://snapt.t15.org/melanie/real_estates/images/house1.jpg",
"rating": 5 500 000,
"releaseYear": 2014,
"genre": ["Spacious open lounge and kitchen"]
},
{
"title": "Kisumu",
"image": "http://snapt.t15.org/melanie/real_estates/images/house2.jpg",
"rating": 1 700 000,
"releaseYear": 2014,
"genre": ["high end townhouse."]
},
{
"title": "Mombasa",
"image": "http://snapt.t15.org/melanie/real_estates/images/house3.jpg",
"rating": 68 000,
"releaseYear": 2014,
"genre": ["Its fully fitted kitchedn pantry with a beautyful backyard."]
}
]
I would like to implement search of title like Kisumu and the result to be displayed will be from this part only so that i parse this alone:
[
{
"title": "Kisumu",
"image": "http://snapt.t15.org/melanie/real_estates/images/house2.jpg",
"rating": 1 700 000,
"releaseYear": 2014,
"genre": ["high end townhouse."]
}
]
Is there a way of achieving the above?
I am open to ideas and suggestions and any help will be appreciated.
Upvotes: 2
Views: 891
Reputation: 700
this method give resualt of server and title as you want and returns search result as JSONObject
private JSONObject SearchMethod(String result,String Key)
{
//result is your server response
//Key is Kisumu
JSONArray json = new JSONArray(result);
for(int i=0;i<json.length();i++){
JSONObject e = json.getJSONObject(i);
if(e.c.getString("title").contains(Key))
return e ;
}
return null;
}
Upvotes: 0
Reputation: 10083
You can't search json directly. Convert the json to List
Java classes. Then use Java API like Predicate
to find necessary java class that satisfy your condition. For eg: Title as Kusumu as you asked.
Which will limit the list of classes to one that satisfy the condition. Then convert the java class back to json if you need Json.
Note: You can use GSON
for easy class <-> json
conversion
UPDATE
For converting Json to Java classes
List<ModelClass> models = new Gson().fromJson(yourJsonString, ModelClass.java);
Then using predicate
public static Predicate<ModelClass> isHavingTitle() { return p -> p.getTitle().contains("Kusumu"); }
In Java 8 predicate filtering can be done like below in other case you can just google it. This is a sample
public static List<ModelClass> filterEmployees (List< ModelClass > models, Predicate< ModelClass > predicate) {
return models.stream().filter( predicate ).collect(Collectors.<ModelClass>toList());
}
I didn't compile any of this :)
String filteredJson = new Gson().toJson(models);
Upvotes: 2