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!
Related
How would I be able to generate a new object based on the object names below. What I am trying to do here is that when there is no Object1, gson will generate Object1 with the values below and when there is Object1, gson will generate Object2 and so on.
{
"Object1": {
"Name": "Object1",
"Color": "Orange",
"Food": "Pizza"
},
"Object2": {
"Name": "Object2",
"Color": "Blue",
"Food": "Pineapple"
}
}
Generating an unique property in your class object means you could dynamically have a class lets say Example.
FoodData {
var object1 : Food?
var object2 : Food?
// And so on...
}
For me this seems like a structural problem. Your response should be specific to the data structure you have and need. A more acceptable approach would be:
[
{
"Name": "Object1",
"Color": "Orange",
"Food": "Pizza",
"someAttr" : "Object1"
},
{
"Name": "Object2",
"Color": "Blue",
"Food": "Pineapple",
"someAttr" : "Object2"
}
]
And then it would make more sense to have a list of food like :
FoodData {
var listFood: List<Food>?
}
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.
I have a scenario where I need to duplicate an object (after or before saving it to Parse) only changing one field.
The problem is, I can't figure out how to find the stop condition when saving this new object and the afterSave callback getting called again and again.
My object:
{
"createdAt": "2015-02-21T23:25:03.525Z",
"creator": {
"__type": "Pointer",
"className": "_User",
"objectId": "2k9OzzBrPr"
},
"date": {
"__type": "Date",
"iso": "2015-02-21T22:46:39.048Z"
},
"description": "Hdheha",
"from": {
"__type": "Pointer",
"className": "_User",
"objectId": "Sd9B1XyZVL"
},
"has_accepted": false,
"has_answered": false,
"objectId": "YQCWRo0j2V",
"status": 0,
"to": {
"__type": "Pointer",
"className": "_User",
"objectId": "2k9OzzBrPr"
},
"updatedAt": "2015-02-21T23:25:03.525Z",
"value": 2.3499999046325684
}
My (try) server code:
function saveMirrorDebit(request) {
var toUser = request.object.get("to");
var fromUser = request.object.get("from");
var invertedDebit = request.object;
var Debit = Parse.Object.extend("Debit");
var query = new Parse.Query(Debit);
query.equalTo("parent_debit", {
__type : "Pointer",
className : "Debit",
objectId : invertedDebit.id
});
query.find({
success : function (debit) {
if (debit) {
console.log('debito nao nulo');
} else {
console.log('debito nulo, criando o espelho invertido');
var newDebit = new Debit();
newDebit.set("creator", invertedDebit.get("creator"));
newDebit.set("from", toUser);
newDebit.set("to", fromUser);
newDebit.set("value", -invertedDebit.get("value"));
newDebit.set("parent_debit", {
__type : "Pointer",
className : "Debit",
objectId : invertedDebit.id
});
newDebit.save(null);
}
},
error : function (error) {
console.log(error);
}
});
}
Which is called on afterSave:
Parse.Cloud.afterSave("Debit", function (request) {
...
saveMirrorDebit(request);
...
}
How can I approach this ?
Thanks
First, I wouldn't recommend you duplicating any object... What are you trying to achieve?
Anyhow, in an afterSave, you can achieve what you want. Note that the beforeSave could save you one API call.
Parse.Cloud.afterSave("Debit", function (request) {
var debit = request.object;
if (!(debit.has("duplicated"))){
var Debit = Parse.Object.extend("Debit");
var duplicated_debit = new Debit();
duplicated_debit.set("creator", debit.get("creator"));
duplicated_debit.set("date", debit.get("date"));
duplicated_debit.set("from", debit.get("from"));
// repeat as many times as needed, include your "change logic here"
// that's where the magic happens
duplicated_debit.set("duplicated",true);
debit.set("duplicated",true);
Parse.Object.saveAll([duplicated_debit,debit]);
}
}
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
{
"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.