Android JSONObject : Search function - android

I am trying to search from JSON code that has been received beforehand..
I was wondering are there any efficient way to search specific object?
Or should i use straight forward search like looping and if statement?
I have parsing the JSON successfully, and it stored in my String variable..
The JSON contains Array of Objects..
Now i want to search for specific ObjectName and get the Whole Objects..
The JSON will be like
[
{
"name":"blank",
"date":"2014-06-05T00:44:30Z",
"boolean":null,
},
{
"name":"hello",
"date":"2013-05-04T00:43:20Z",
"boolean":null,
}
]
I want to search for name = "hello" and get the last Array returned
Can anyone show me how?
Thanks a lot!

You can use something like this:
String name;
JSONObject searchObject;
JSONArray array = new JSONArray(yourJsonString);
for (int i = 0; i < array.length(); i++) {
JSONObject currObject = array.getJSONObject(i);
name = currObject.getString("name");
if(name == "hello")
{
searchObject = currObject
}
}
return searchObject

For big data you can't use search in every element imagin you have a 50K user you can't search in every 50k title to found your element I advise you to the backend - Web Developer - do this it will be easier to you and more faster how you can do this?
You just need a space to pass search text in JSON Url then post it and retrieve searched data from him

Try to use a web server with (PHP) and set your search element in GET like this.
Then the php search function will give you the full Json needed to your search. Also you can set pagination for this search like this.

Related

How to parse JSON data when Json root is not an array but an object and vice-versa, based on different urls?

I am trying to build an android app that uses the github api.
I am facing an issue with JSON parsing.
I have a function that looks for JSONArray and produces the corresponding JSON data to show them in the UI, but the problem is the function works only when the JSON root is an array.
For ex-
when the url is "https://api.github.com/users", it works perfect, since the root is an array but now when I go to url such as "https://api.github.com/users/mojombo", the JSON root becomes an object. How do I parse it now in order to show the data in the UI ??
Do I have to write separate function for JSONObjects??
**The java function is **
private void makeJSON(String res) throws JSONException {
JSONArray root = new JSONArray(res);
for (int i =0; i<root.length();i++){
JSONObject jsonObject= root.getJSONObject(i);
String name = jsonObject.getString("login");
int id = jsonObject.getInt("id");
}
}
The answer is yes. Here you try to parse different types of objects (users list and particular user info) in single function. This is violation of single responsibility principle.
You can divide this function in 2 (to parse users list and user data) but better is to use Retrofit 2 for this.

Android JSON fetching - No value for (value) eventhough the value exists

I have a valid json link, and I want to fetch data from it.
This is my code, for fetching data:
try {
JSONObject topicsObject = new JSONObject(getTopicsJSON);
JSONArray topics = topicsObject.getJSONArray("Topics");
for (int i = 0; i<topics.length();i++){
SuperTrenerTopic stt = new SuperTrenerTopic();
JSONObject sub_topic = topics.getJSONObject(i);
JSONObject topic = sub_topic.getJSONObject("Topic");
...
}
On the last line of code, I get ann error saying org.json.JSONException: No value for Topic.
Following screenshot shows that it is not correct, as I Log-ed the recieved JSON, and you can clearly see that in fact, there IS a "Topic" object out there:
First Log represents the first part of an entire Json responce, and the second one is the Topic object itself.
Here is another screenshot of the JSON format i took from my browser:
You can notice that "Topic" and "meta" objects are on the same hierarchy level.
I fetch "meta" object with no problem whatsoever, using the same code I would use for fetching 'Topics", but for some reason, fetching "Topics" doesn't work out.
here is the code I successfully use to fetch "meta' object:
JSONObject meta = sub_topic.getJSONObject("meta");
What could be the cause of this?
Is there something realy obvious that I'm missing out?

Android : how to get jsonarray from json object in different ways

I know how to get jsonarray from jsonobject. I am doing like below code to get jsonarray.
JSONObject recvJson = new JSONObject(holder.toString());
String numberByte= (String) recvJson.get("data");
String ts = (String) recvJson.get("time");
JSONObject temp2 = new JSONObject("{ \"data\" : " + numberByte+ "}");
JSONArray recvJarray = temp2.getJSONArray("data");
for (int i = 0; i < recvJarray.length(); i++)
{
byteArray[i] = (byte) recvJarray.getInt(i);
}
But don't want to use for-loop, without using for-loop or any other loop want to retrieve jsonarray data values.
How should I do ?? I have done google & saw many forums but dint succeed to retrieve data without using for-loop.
for example : I ll be getting 80 - 100 packets of 1024bytes per second from server, I want to retrieve this data & store it into bytearray. By usingf for-loop its taking around 300ms- 400ms and I am loosing many packets between that. So I want to use different approach. If any Idea or solution for cracking this.
Help will be appreciated !!
You can use GSON to parse the json objects. It is much faster and easier to decode json data.
Check these links.
Gson1, Gson2
try usig gson
it uses java reflection to convert objects to json and json to object with simple methods
toJson(),fromJson() (and it works for object arrays and lists too)
but you have to write the proper classes for the jsons (with all fields)
read the documentation.

Accessing an object from JSON in Android

I have a question that I am a little bit confused about. I am quite new to JSON and getting JSON values in the android API. I am trying to access an array within the response I get. the JSON code I am getting is something like this:
Response:
{
"event": {
"participants": []
},
"status": "success"
}
How would I access the participants array and store their values. This is what I am trying at the moment... but I dont appear to be getting what I want.
try{
//get the JSON values from the URL.
JSONObject json = jParser.getJSONFromUrl("http://somesite.com/api/find?"+"somevar="+someJavaStringVar);
json_event = json.getJSONObject("event");
JSONArray json_array_participants = json_event.getJSONArray("participants");
} catch(JSONException e) {
}
The thing I am mostly confused about is... what is the arrays type equivalent to. Any advice or reasoning as to the correct way to get ahold of that variables value would be great... thanks guys.. :).
Think JSON is really just a key-value pairing. The JSONArray type is just an array full of objects (like Object[]) - it has no idea what the objects it contains are or what they're to be used for. Its up to you to assign meaning to the JSON stream based on what you know of the source. From what I see of your code, most of it looks fine, though I don't know what your jParser.getJSONFromURL() is doing. Typically, you would build the JSON from the response string like so:
String jsonString = getJSONFromUrl("http://somesite.com/api/find?"+"somevar="+someJavaStringVar);
JSONObject json = new JSONObject(jsonString)
JSONObject json_event = json.getJSONObject("event");
JSONArray json_array_participants = json_event.getJSONArray("participants");
You can iterate through the array like any other array to get subobjects or whatever:
for(int i=0; i < json_array_participants.getLength(); i++) {
JSONObject participant = json_array_participants.getJSONObject(i);
// Do stuff
}
As a side note - I WOULDN'T use GSON until you understand the underlying protocol, at least a little - because you never know when you might want to parse your JSON from a different language for some reason.
I would strongly recommend to use gson instead as your preferred parser since it will do all the job of serializing and deserializing for you except creating the domain objects.
This tutorial should get you going:
http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
This will depend on what the server is supposed to return. It could be an array of anything and if this is a public service, there should be a specification to go off of.
If you are in charge of the server portion as well, and you have a backing object, Google's GSON library is extremely easy to use. It will also keep type information straight.

How to display RSS in Android?

I'm using JSON in my app and I have a button "RSS", after clicking on which I want to see the RSS feed. While logging in, I also use JSON, but everything is done in background and the next view does not depend on JSON object. In LogCat I can see something like this {"response":{"#attributes":{"count":"4","all_results_count":"4","page":"1"},"news":[{"content_id":"43366","date_added":"04-01-2010","content_title":"New News","content_data":"mika"},{"content_id":"111443","date_added":"04-11-2008","content_title"..... But how can I actually display this on Android's screen?
Use JSONTokener to parse the JSON string.
string json = getYourFeed() // some method to retrieve the json response.
JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
int count = JSONObject response = object.getJSONObject("response").getJSONObject("#attributes").getInt("count");
JSONArray array = object.getJSONObject("response").getJSONArray("news");
for (int i=0; i<count; i++) {
JSONObject newsItem = array.getJSONObject(i);
Log.d("RSSReader", newsItem.getString("content_title");
}
use the get... methods of JSONObject to retrieve the rest the same way.
Update, based on your comment: I would start it simple, and then add more complexity as you get a feel for these controls. Create a String[] array with your news titles and add it to the list using an ArrayList adapter. It's very easy to use. Add an OnItemClickListener that shows a Toast with the full content.
Then, you can move to a SimpleAdapter version with a multiple columns ListView and perhaps a TabActivity that shows the full news.
http://ykyuen.wordpress.com/2010/01/03/android-simple-listview-using-simpleadapter/
http://developer.android.com/resources/tutorials/views/hello-tabwidget.html
What code are you using to get those outputs?
I would parse it with something like a 'SAXParser' and Display it using an 'ListView'...

Categories

Resources