Android sdk parsing unknow JSON array key name and quantity - android

{
"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.

Related

How to parse json array having dynamic keys using Retrofit 2

I am trying to fetch json response using retrofit 2. My json response looks like this :
[
0 : {
type : "video",
format : "mp4",
size : "10mb"
},
1 : {
type : "audio",
format : "mp3",
size : "10mb"
},
2 : {
type : "text",
format : "pdf",
size : "10mb"
}
]
How should my model class look like? I can't understand as it has dynamic keys.
This is not a valid Json as you can try that on https://jsonlint.com/ , you can change your response to :
[
{
"type":"video",
"format":"mp4",
"size":"10mb"
},
{
"type":"audio",
"format":"mp3",
"size":"10mb"
},
{
"type":"text",
"format":"pdf",
"size":"10mb"
}
]
first of all this is invalid/incomplete JSON. The valid version would look something like this
{
"items": [
{
"0": {
"type": "video",
"format": "mp4",
"size": "10mb"
}
},
{
"1": {
"type": "audio",
"format": "mp3",
"size": "10mb"
}
},
{
"2": {
"type": "text",
"format": "pdf",
"size": "10mb"
}
}
]
}
and it would safely deserialize to this
class Item{
String type;
String format;
String size;
}
class Response{
List<Map<Integer,Item>> items;
}
//....
Response response = new Gson().fromJson(yourJson, Response.class);
As an alternative solution, as I am sure you can't change the JSON format, change the [] to {} in your JSON string and deserialize it like this
Map fieldMap = (Map)new Gson().fromJson(json, Map.class);
it should give you a LinkedTreeMap of all your data
So, as people already said, if you change your json to be valid:
[
{
"type":"video",
"format":"mp4",
"size":"10mb"
},
{
"type":"audio",
"format":"mp3",
"size":"10mb"
},
{
"type":"text",
"format":"pdf",
"size":"10mb"
}
]
Then you can create your class, for instance:
public class Test {
public String type;
public String format;
public String size;
}
And then, with Gson:
Type testType = new TypeToken<ArrayList<Test>>(){}.getType();
ArrayList<Test> list = new Gson().fromJson(json, testType);
On the other hand, with retrofit2 you can get the Gson converter to do the job for you.

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 :)

Parsing JSON, array within an array (Android)

I'm trying to parse weather information from a http://www.worldweatheronline.com JSON feed. This is the format that it comes in:
{ "data" : { "current_condition" : [ { "cloudcover" : "75",
"humidity" : "100",
"observation_time" : "10:01 PM",
"precipMM" : "0.0",
"pressure" : "1015",
"temp_C" : "3",
"temp_F" : "37",
"visibility" : "4",
"weatherCode" : "143",
"weatherDesc" : [ { "value" : "Mist" } ],
"weatherIconUrl" : [ { "value" : "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0006_mist.png" } ],
"winddir16Point" : "N",
"winddirDegree" : "360",
"windspeedKmph" : "11",
"windspeedMiles" : "7"
} ],
So there is the current_condition JSONArray, which I have managed to obtain values from. But then how do I read the values from the inner arrays weatherDesc or weatherIconUrl?
Here is my code for reading precipMM, pressure, temp_C, etc:
String precipMM = null;
try {
JSONObject data = json.getJSONObject("data");
JSONArray current_condition = data.getJSONArray("current_condition");
for(int i = 0; i < current_condition.length(); i++) {
precipMM = current_condition.getJSONObject(i).getString("precipMM");
}
} catch (JSONException e) {
e.printStackTrace();
}
It's as simple as
current_condition.getJSONArray()
As also with json parsing I would suggest looking at this library
http://jackson.codehaus.org/
EDIT After you comment
The code you posted could be improved a lot. You are iterating through the array for each value. You can do the same thing with the array. Just call .getJsonArray(), instead of .getJsonObject(). However this means your code is throwing an error for each of the other values. I would again recommend the Jackson library
weatherDesc and weatherIconUrl are provided as array, so you can access by item i.e. inside a for loop.
Just use same command as you do it for current_condition

JSON object parsing for text and image

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

get coordinates from JSON from google maps

I'm getting my position from an address, I use this website:
I get JSON data, but I dont know how to read it in my Android app.
{
"name": "plaza mayor 1 madrid España",
"Status": {
"code": 200,
"request": "geocode"
},
"Placemark": [ {
"id": "p1",
"address": "Plaza Mayor, 1, 28012 Madrid, España",
"AddressDetails": {
"Accuracy" : 8,
"Country" : {
"AdministrativeArea" : {
"AdministrativeAreaName" : "Comunidad de Madrid",
"SubAdministrativeArea" : {
"Locality" : {
"LocalityName" : "Madrid",
"PostalCode" : {
"PostalCodeNumber" : "28012"
},
"Thoroughfare" : {
"ThoroughfareName" : "Plaza Mayor, 1"
}
},
"SubAdministrativeAreaName" : "Madrid"
}
},
"CountryName" : "España",
"CountryNameCode" : "ES"
}
},
"ExtendedData": {
"LatLonBox": {
"north": 40.4164186,
"south": 40.4137207,
"east": -3.7053139,
"west": -3.7080118
}
},
"Point": {
"coordinates": [ -3.7066379, 40.4150359, 0 ]
}
} ]
}
How can I read the "coordinates" tag?
Thank you in advance!
parse it, to begin with, then access the various elements :
JSONObject response = new JSONObject(responseAsString);
JSONObject point = response.getJSONArray("Placemark").getJSONObject(0).getJSONObject("Point");
double lat = point.getJSONArray("coordinates").getDouble(0);
and so on
I would suggest using some sort of framwork to handle your Json data, here's a good aexample. Then you can handle your data as a regular object.
Sending and Parsing JSON Objects
Good luck!

Categories

Resources