JSON object parsing for text and image - android

I'm trying to parse the following JSON string returned by httpResponse:
{ "message" : "List of top ten checkin Men.",
"success" : "True",
"top_ten_checkin_men" : [ { "City_name" : "Mumbai",
"is_block" : "no",
"is_favorite" : "no",
"is_friend" : "no",
"last_step_in" : "Pride Hotels",
"online" : "1",
"points" : "3800",
"request_pending" : "no",
"user_thumbphoto" : "",
"userage" : "26",
"userbodytype" : "3",
"userfname" : "John",
"usergender" : "Male",
"userid" : "191",
"userlname" : "Aarmani",
"userlookingfor" : "Female",
"useronlinestatus" : "Yes",
"userphoto" : ""
},
{ "City_name" : "New York",
"is_block" : "no",
"is_favorite" : "no",
"is_friend" : "no",
"last_step_in" : "The House of MG",
"online" : "1",
"points" : "4450",
"request_pending" : "no",
"user_thumbphoto" : "http://anburaj.com/lockme/uploads/users/188/thumb_121840970.jpg",
"userage" : "31",
"userbodytype" : "3",
"userfname" : "Williams",
"usergender" : "Male",
"userid" : "188",
"userlname" : "Johens",
"userlookingfor" : "Female",
"useronlinestatus" : "Yes",
"userphoto" : "http://anburaj.com/lockme/uploads/users/188/121840970.jpg"
}
]
}
and so on.
What I should I take for jsonarray and what should be gone for jsonobject?

[] defines a JSONArray (for instance top_ten_checkin_men). {} defines a JSONObject.
It's worth to take the time to know about the JSON format here:

"[]" represent array and "{}" is an object

What you have here is a JSONObject with success and message fields and a JSONArray top_ten_checkin_men
So something like :
JSONObject json = new JSONObject(yourString);
String message = json.getString("message");
String success = json.getString("success");
JSONArray array = json.getJSONArray("top_ten_checkin_men");
should do what you want

Related

Get data from Firebase database using child name from unknown push key

Using android studio ( android )
how to Get data from Firebase database
using child value from unknown pushed key
as you can see in the picture friends
I'm trying to get data where
topicimage4 = 0
But I don't have the random key Firebase pushed
Firebase database
I searched alot about this Issue but I didn't found anything or
I found questions with no answers in this website
I tried also the following
myRef.child("*").orderByChild("topicimage4").equalTo("0")
myRef.child("?").orderByChild("topicimage4").equalTo("0")
myRef.orderByChild("topicimage4").equalTo("0")
myRef.orderByKey().orderByChild("topicimage4").equalTo("0")
UPDATE
here my Json tree as text
Is there any way to access to the topicimage4 child without having the Randrom key ? thnx
{
"-L5YppUZa3dGBvDUgnYi" : {
"paidmoney" : "400",
"paidmoneytype" : "1",
"topiccat" : "1",
"topiccon" : "0",
"topicemail" : "",
"topicimage1" : "null",
"topicimage2" : "null",
"topicimage3" : "null",
"topicimage4" : "0",
"topicimage5" : "21",
"topicname" : "مطلوب انسات للعمل ضمن صالون نسائي طريق عام جزين",
"topicphone" : "70645725",
"topicresouresname" : "",
"topicresouresurl" : "",
"topictext" : "في حال طلب منك الاتصال دولار اضافي على الدقيقة قم بإغلاق الخط \r\n\r\nمطلوب انسات للعمل ضمن صالون نسائي طريق عام جزين\r\n\r\n\r\nنحن نحاول قدر الامكان ضبط جميع انواع الوظائف المقدمة نشكر لكم اهتمامكم ومساعدتكم\r\n",
"topictimed" : "17",
"topictimeh" : "01",
"topictimei" : "57",
"topictimem" : "02",
"topictimey" : "18",
"userimage" : "0"
},
"-L5Yq6VJoOAN7dUKDO9O" : {
"paidmoney" : "400",
"paidmoneytype" : "1",
"topiccat" : "1",
"topiccon" : "0",
"topicemail" : "",
"topicimage1" : "null",
"topicimage2" : "null",
"topicimage3" : "null",
"topicimage4" : "0",
"topicimage5" : "0",
"topicname" : "يلزمنا انسه ذات مظهر لائق",
"topicphone" : "81614696",
"topicresouresname" : "",
"topicresouresurl" : "",
"topictext" : "في حال طلب منك الاتصال دولار اضافي على الدقيقة قم بإغلاق الخط \r\n\r\nيلزمنا انسه زات مظهر لائق للعمل في اكس برس عالاوتستراد بدوام كامل للمراجعه وتس اب التفاصيل موجوده كامله\r\n\r\n\r\n\r\nنحن نحاول قدر الامكان ضبط جميع انواع الوظائف المقدمة نشكر لكم اهتمامكم ومساعدتكم\r\n",
"topictimed" : "17",
"topictimeh" : "01",
"topictimei" : "58",
"topictimem" : "02",
"topictimey" : "18",
"userimage" : "0"
}
}

Get multiple Objects from Json Android

I want to get data from this but its to confusing, how to do it.
I want to access legs. In legs distance then text.
Then after steps, in steps again distance and then text.
In "routes" ==> "legs" --> distance --> text
Then to get driving steps
"routes" ==> "legs" ==> "steps" --> distance --> text
First there is object then array again object its too confusing. Any help would be appreciated.
{
"geocoded_waypoints" : [
{
"geocoder_status" : "OK",
"place_id" : "ChIJ2QeB5YMEGTkRYiR-zGy-OsI",
"types" : [ "locality", "political" ]
},
{
"geocoder_status" : "OK",
"place_id" : "ChIJ2afeeFcxOzkRL9RVTscv17o",
"types" : [ "locality", "political" ]
}
],
"routes" : [
{
"bounds" : {
"northeast" : {
"lat" : 31.55462439999999,
"lng" : 74.3571711
},
"southwest" : {
"lat" : 30.1981178,
"lng" : 71.4687352
}
},
"copyrights" : "Map data ©2016 Google",
"legs" : [
{
"distance" : {
"text" : "348 km",
"value" : 347978
},
"duration" : {
"text" : "4 hours 49 mins",
"value" : 17335
},
"end_address" : "Multan, Pakistan",
"end_location" : {
"lat" : 30.1981178,
"lng" : 71.4687352
},
"start_address" : "Lahore, Pakistan",
"start_location" : {
"lat" : 31.55462439999999,
"lng" : 74.3571711
},
"steps" : [
{
"distance" : {
"text" : "67 m",
"value" : 67
},
"duration" : {
"text" : "1 min",
"value" : 9
},
"end_location" : {
"lat" : 31.5549532,
"lng" : 74.3565735
},
"html_instructions" : "Head \u003cb\u003enorthwest\u003c/b\u003e on \u003cb\u003eAllama Iqbal Rd\u003c/b\u003e",
"polyline" : {
"points" : "k_r_Ei{ydM[r#e#bA"
},
"start_location" : {
"lat" : 31.55462439999999,
"lng" : 74.3571711
},
"travel_mode" : "DRIVING"
},
Manual method:
In few words Json gives you objects (beetwen { } ) or array (beetwen [ ] ). To get sth from deep in json you have to go through each level. You put only fragment of json, but I closed it and we have at start json object (because main braces are {} ):
{
"geocoded_waypoints" : [
{
"geocoder_status" : "OK",
"place_id" : "ChIJ2QeB5YMEGTkRYiR-zGy-OsI",
"types" : [ "locality", "political" ]
},
{
"geocoder_status" : "OK",
"place_id" : "ChIJ2afeeFcxOzkRL9RVTscv17o",
"types" : [ "locality", "political" ]
}
],
"routes" : [
{
"bounds" : {
"northeast" : {
"lat" : 31.55462439999999,
"lng" : 74.3571711
},
"southwest" : {
"lat" : 30.1981178,
"lng" : 71.4687352
}
},
"copyrights" : "Map data ©2016 Google",
"legs" : [
{
"distance" : {
"text" : "348 km",
"value" : 347978
},
"duration" : {
"text" : "4 hours 49 mins",
"value" : 17335
},
"end_address" : "Multan, Pakistan",
"end_location" : {
"lat" : 30.1981178,
"lng" : 71.4687352
},
"start_address" : "Lahore, Pakistan",
"start_location" : {
"lat" : 31.55462439999999,
"lng" : 74.3571711
},
"steps" : [
{
"distance" : {
"text" : "67 m",
"value" : 67
},
"duration" : {
"text" : "1 min",
"value" : 9
},
"end_location" : {
"lat" : 31.5549532,
"lng" : 74.3565735
},
"html_instructions" : "Head \u003cb\u003enorthwest\u003c/b\u003e on \u003cb\u003eAllama Iqbal Rd\u003c/b\u003e",
"polyline" : {
"points" : "k_r_Ei{ydM[r#e#bA"
},
"start_location" : {
"lat" : 31.55462439999999,
"lng" : 74.3571711
},
"travel_mode" : "DRIVING"
}]
}
]
}
]
}
Let's say you have this as a String named "jsonString". You create json object like this:
JSONObject jsonObject = new JSONObject(jsonString);
Than you needs "routes" that is json array (between [] braces). You create this array going deeper into your main jsonObject:
JSONArray routesArray = jsonObject.getJSONArray("routes");
To go through each array element (that are json objects) you iterate like this:
for (int i = 0; i < routesArray.length(); i++) {
//do sth
}
And you get your "legs" like this:
JSONObject routeObject = routesArray.get(i);
routeObject.get("legs");
And deeper and deeper like above.
Automatically
It's much easier to use Gson library and some Json Pojo parsers.
You import gson in your build.gradle:
compile 'com.google.code.gson:gson:2.4'
Than you can use this parser. Select source type "JSON" and "Annotation style" Gson. Put your json in text box and click Preview or download ZIP. You can also put your package name and main class name or rename it manually later. You will be given multiple model classes with top one called "Example" or your name. It consists of two fields:
public class Example {
#SerializedName("geocoded_waypoints")
#Expose
private List<GeocodedWaypoint> geocodedWaypoints = new ArrayList<GeocodedWaypoint>();
#SerializedName("routes")
#Expose
private List<Route> routes = new ArrayList<Route>();
Add all classes to your project and than you just parse your jsonString to your main class like this:
Example mainClassObject = new Gson().fromJson(jsonString, Example.class);
And now you can access routes from this object. And legs from routes and deeper and deeper...
Please try below code to parse provided json keys value :
private void parseJson(String jsonString){
ArrayList<String> legsDistanceList = new ArrayList<>();
ArrayList<String> legStepsDistanceList = new ArrayList<>();
try{
JSONObject rootJson = new JSONObject(jsonString);
if(rootJson.has("routes")) {
JSONArray routesJsonArray = rootJson.getJSONArray("routes");
for(int i=0;i<routesJsonArray.length();i++){
JSONObject routeJson = routesJsonArray.getJSONObject(i);
if(routeJson.has("legs")){
JSONArray legsJsonArray = routeJson.getJSONArray("legs");
for(int j=0;j<legsJsonArray.length();j++){
JSONObject legJson = legsJsonArray.getJSONObject(j);
if(legJson.has("distance")){
JSONObject distanceJson = legJson.getJSONObject("distance");
legsDistanceList.add(distanceJson.getString("text"));
}
if(legJson.has("steps")){
JSONArray stepsJsonArray = legJson.getJSONArray("steps");
for(int k=0;k<stepsJsonArray.length();k++){
JSONObject stepJson = stepsJsonArray.getJSONObject(k);
if(stepJson.has("distance")){
JSONObject stepDistanceJson = stepJson.getJSONObject("distance");
legStepsDistanceList.add(stepDistanceJson.getString("text"));
}
}
}
}
}
}
}
}catch (Throwable e){
e.printStackTrace();
}
Log.i("Legs Distance ",legsDistanceList.toString());
Log.i("Legs Steps Distance ",legStepsDistanceList.toString());
}
I think above code might be difficult for you to understand at this stage but once you understand then it will more helpful to you for future JSON parsing stuff.
you can third parties(Gson, Logan Square,etc..) for parsing. If you are trying to access it directly. Below you can find the sample code to access the "legs" array.
Let us assume
JsonObject jsonObject = new JsonObject("json string");
this "jsonObject" is the full json value, from which you want to access the "legs" array. In this scenario the "legs" array is inside the "routes" array. So we need to get the "routes" array first and loop that array and get the "legs" array from each object and store in POJO class or if you want to fetch the "text" alone from the "distance" means you can store that in arraylist or string which you need. Below is the sample code to get the text alone.
JsonArray routesArray = jsonObject.optJsonArray("routes");
if (routesArray != null) {
for (int i = 0; i < routesArray.length(); i++) {
JsonArray legsArray = routesArray.get(i).optJsonArray("legs");
if (legsArray != null) {
for (int i = 0; i < legsArray.length(); i++) {
JsonObject legObject = legsArray.get(i);
JsonObject distanceObject = legObject.optJsonObject("distance");
String textValue = distanceObject.optString("text");
}
}
}
}
Hope this is helpful :)

Android Firebase, server side filtering for Recyclerview

Following is my firebase data structure
{
"ticketing" : {
"1476639649079-mahto" : {
"agentId" : 0,
"agent_status" : "1_Dispatched",
"approverId" : 0,
"contractorId" : 0,
"dateTime" : "16-10-2016 13:40 PM",
"priority" : "MEDIUM",
"requester" : {
"issue" : "issue 3",
"location" : "location 3",
"priority" : "Medium",
"shop" : "shop 3",
"site" : "site 3",
"userInfo" : {
"email" : "m#gmail.com",
"firstname" : "mahto",
"isLoggedin" : true,
"lastname" : "pancha",
"loggedin" : true,
"number" : "123123123",
"password" : "q",
"role" : "fieldagent",
"userid" : "2",
"username" : "q"
}
},
"requesterId" : 2,
"status" : "Incoming",
"ticketNumber" : "1476639649079-mahto"
},
"1476741838857-mahto" : {
"agentId" : 1,
"agent_status" : "1_Incoming",
"approverId" : 0,
"contractorId" : 0,
"dateTime" : "17-10-2016 18:03 PM",
"priority" : "HIGH",
"requester" : {
"issue" : "Description 3",
"location" : "Location 3",
"priority" : "HIGH",
"shop" : "shop 3",
"site" : "site 3",
"userInfo" : {
"email" : "m#gmail.com",
"firstname" : "mahto",
"isLoggedin" : true,
"lastname" : "pancha",
"loggedin" : true,
"number" : "123123123",
"password" : "q",
"role" : "fieldagent",
"userid" : "2",
"username" : "q"
}
},
"requesterId" : 2,
"status" : "Incoming",
"ticketNumber" : "1476741838857-mahto"
}
}
}
Database refrence
mDatabase = FirebaseDatabase.getInstance().getReference().child("ticketing");
mDatabase.orderByChild("agent_status").equalTo("1_Incoming");
and attached to recyclerview adapter
mAdapter = new FirebaseRecyclerAdapter<Ticket, AgentTicketHolder>(Ticket.class, R.layout.agent_ticket_cardview, AgentTicketHolder.class, mDatabase) { .. }
My expected result is that i will get only one node i.e 1476741838857-mahto which has agent_status value equal to 1_Incoming.
But i'am getting both the nodes in my recylerview.
When you call filtering methods, the Firebase SDK returns a new object for the resulting query. So you need to capture the reference to that object and pass that into the adapter:
mDatabase = FirebaseDatabase.getInstance().getReference().child("ticketing");
Query query = mDatabase.orderByChild("agent_status").equalTo("1_Incoming");
mAdapter = new FirebaseRecyclerAdapter<Ticket, AgentTicketHolder>
(Ticket.class, R.layout.agent_ticket_cardview, AgentTicketHolder.class, query) { .. }

How to decode json+collection in Android [duplicate]

This question already has answers here:
Sending and Parsing JSON Objects in Android [closed]
(11 answers)
Closed 7 years ago.
I have a json+collection string as following:
//code formated
{ "collection" :
{
"version" : "1.0",
"href" : "http://example.org/friends/",
"links" : [
{"rel" : "feed", "href" : "http://example.org/friends/rss"}
],
"items" : [
{
"href" : "http://example.org/friends/jdoe",
"data" : [
{"name" : "full-name", "value" : "J. Doe", "prompt" : "Full Name"},
{"name" : "email", "value" : "jdoe#example.org", "prompt" : "Email"}
],
"links" : [
{"rel" : "blog", "href" : "http://examples.org/blogs/jdoe", "prompt" : "Blog"},
{"rel" : "avatar", "href" : "http://examples.org/images/jdoe", "prompt" : "Avatar", "render" : "image"}
]
},
{
"href" : "http://example.org/friends/msmith",
"data" : [
{"name" : "full-name", "value" : "M. Smith", "prompt" : "Full Name"},
{"name" : "email", "value" : "msmith#example.org", "prompt" : "Email"}
],
"links" : [
{"rel" : "blog", "href" : "http://examples.org/blogs/msmith", "prompt" : "Blog"},
{"rel" : "avatar", "href" : "http://examples.org/images/msmith", "prompt" : "Avatar", "render" : "image"}
]
},
{
"href" : "http://example.org/friends/rwilliams",
"data" : [
{"name" : "full-name", "value" : "R. Williams", "prompt" : "Full Name"},
{"name" : "email", "value" : "rwilliams#example.org", "prompt" : "Email"}
],
"links" : [
{"rel" : "blog", "href" : "http://examples.org/blogs/rwilliams", "prompt" : "Blog"},
{"rel" : "avatar", "href" : "http://examples.org/images/rwilliams", "prompt" : "Avatar", "render" : "image"}
]
}
],
"queries" : [
{"rel" : "search", "href" : "http://example.org/friends/search", "prompt" : "Search",
"data" : [
{"name" : "search", "value" : ""}
]
}
],
"template" : {
"data" : [
{"name" : "full-name", "value" : "", "prompt" : "Full Name"},
{"name" : "email", "value" : "", "prompt" : "Email"},
{"name" : "blog", "value" : "", "prompt" : "Blog"},
{"name" : "avatar", "value" : "", "prompt" : "Avatar"}
]
}
}
}
sample linK: http://amundsen.com/media-types/collection/examples/
Can you please help me on how to decode this message. I have to read items , queries into my code and also version etc. I have to do this on android. I am not able to get how to use JSONObject to fetch the items, queries into my code.
For the array objects use JSONArray. Method arr.length() returns elements count, arr.get<type>(position) or just arr.get(position) for getting element.
you may use:
import org.json.JSONException;
import org.json.JSONObject;
in the following way:
try {
JSONObject myObj = new JSONObject("your json string");
} catch (JSONException e) {
e.printStackTrace();
}

Android sdk parsing unknow JSON array key name and quantity

{
"transport" : {
"public" : [
{
"transport_id" : "2",
"transport_name" : "Ferry"
},
{
"transport_id" : "3",
"transport_name" : "Bus"
},
{
"transport_id" : "4",
"transport_name" : "Taxi"
},
{
"transport_id" : "5",
"transport_name" : "Tram"
}
],
"Private" : [
{
"transport_id" : "11",
"transport_name" : "Bicycle"
},
{
"transport_id" : "12",
"transport_name" : "Private Car"
}
],
"Misc" : [
{
"transport_id" : "6",
"transport_name" : "By Foot"
},
{
"transport_id" : "7",
"transport_name" : "Helicopter"
},
{
"transport_id" : "8",
"transport_name" : "Yatch"
}
]
}
}
I was originally developing iOS app which extract the above JSON to a "ListView", but now I am trying to do it in android, i was wondering how I can convert the above JSON to a sectioned List View.
Consider that the array "KEY" (i.e.:"public" , "private"...etc for the above example ) will be unknown and generate dynamically and so is the array quantity.
Thank you so much.
You can Use built-in org.Json Package as following:
String jsonString = "{
'transport' : {
'public' : [ ..."
JSONObject jsonO = new JSONObject(jsonString);
for (String key: jsonO.keys()){
Object o = jsonO.get(key)
if (o instanceof JSONArray){
JSONArray jsonA = (JSONArray)o;
int muberOfItems = jsonA.length();
for(int i = 0; i<numberOfItems; i++){
JSONObject jsonO2 = jsonA.optJSONObject(i)
if (jsonO2 == null) // continue ?
//this object should contain your transportId and transportName
String transportId = jsonO2.getString(0);
String transportName = jsonO2.getString(1);
//parse your Data, you have anything you need (private public etc == key)
//whichValue = i
}
} else { //must be some other value }
}
JsonObjects contains other useful Methods, and can be considered as a HashMap like Object.

Categories

Resources