i was tring to find a solution to get lat and lng as a double
JSONArray arr = jsonObject.getJSONArray("hits");
for (int i = 0; i < arr.length(); i++)
{
String geoloc = arr.getJSONObject(i).getString("_geoloc");
Log.d("geoloc"," : " + geoloc);
}
so what i get is this : geoloc: : {"lat":33.84878,"lng":-5.481698}
What I want is something like this :
double lat = 33.84878;
double lng = -5.481698;
my question is how can i get them any help please. and thank you
You need to convert the String geoloc to JSONObject.
For example:
JSONObject geolocJsonObj = (JSONObject) geoloc;
After you can access to lat:
geolocJsonObj.get("lat")
You can create a class of GeoLocation and push values into the ArrayList of that:
class GeoLocation {
private double lat;
private double long;
GeoLocation(double nLat, double nLong) { this.lat = nLat, this.long = nLong }
// ... Getter and Setter methods
}
You can use parseDouble in order to extract double values from the json object like this:
JSONArray arr = jsonObject.getJSONArray("hits");
List<GeoLocation> aGeoLocationList = new ArrayList<GeoLocation>();
for (int i = 0; i < arr.length(); i++)
{
double latVal = Double.parseDouble(arr.getJSONObject(i).getString("lat"));
double longVal = Double.parseDouble(arr.getJSONObject(i).getString("long"));
aGeoLocationList.add(new GeoLocation(latVal, longVal));
}
Related
I'm trying to add a list of purchases to an array and then be able to perform some calculations based on the doubles in the array. Im having trouble trying to add purchases to the double array
Here's what I have:
public abstract class Customer {
protected String category;
protected String acctNumber;
protected String name;
protected double[] purchases;
protected static final double SALES_TAX_RATE = 0.08;
/**
*Reads in customer data.
*#param acctNumberIn customers account number.
*#param nameIn customers name.
*/
public Customer(String acctNumberIn, String nameIn) {
acctNumber = acctNumberIn;
name = nameIn;
purchases = new double[0];
}
Add purchases method where I'm having problems:
public void addPurchases(double ... pur) {
purchases = Arrays.copyOf(purchases, purchases.length + 1);
int a = purchases.length;
for (int i = 0; i < purchases.length; i++) {
purchases[a] = pur;
}
}
The problem is that pur is of type double[]. So you will need to create a new array with the size of purchases + pur, and copy each element of pur to the end of purchases.
Please try the following code:
public void addPurchases(double ... pur) {
int purchasesLength = purchases.length;
int combinedLength = pur.length + purchasesLength;
purchases = Arrays.copyOf(purchases, combinedLength);
for (int i = purchasesLength, j = 0; i < combinedLength; i++, j++) {
purchases[i] = pur[j];
}
}
Using an ArrayList instead of an array would be much simpler, as well as improve your code performance and quality. To create one to hold your purchases you could do
protected ArrayList<Double> purchases = new ArrayList<Double>();
And then your addPurchases method can easily be simplified to:
public void addPurchases(double... pur) {
for (double purchase : pur) {
purchases.add(purchase);
}
}
pur is an array, double... pur is away that allows you to pass zero or more values to a method, but which are treated as an array from within the method.
With this in mind, you are attempting to assign every element in your purchases array to the same value pur (or a double[]) which obviously won't work.
Instead, you need to get the current length of the array, re-size the array by the length of pur (purchases.length + pur.length), then from the previously last position begin adding in the new elements from pur
Maybe something like...
public void addPurchases(double... pur) {
int start = purchases.length;
purchases = Arrays.copyOf(purchases, purchases.length + pur.length);
for (int i = start; i < purchases.length; i++) {
purchases[i] = pur[i - start];
}
}
Now, any time you think this might be a good idea, you should consider using a List of some kind instead, maybe something like...
public static class Customer {
protected String category;
protected String acctNumber;
protected String name;
protected List<Double> purchases;
protected static final double SALES_TAX_RATE = 0.08;
/**
* Reads in customer data.
*
* #param acctNumberIn customers account number.
* #param nameIn customers name.
*/
public Customer(String acctNumberIn, String nameIn) {
acctNumber = acctNumberIn;
name = nameIn;
purchases = new ArrayList<>(25);
}
public void addPurchases(double... pur) {
for (double p : pur) {
purchases.add(p);
}
}
}
Have a look at the Collections Trail for more details
You can simply do:
public void addPurchases(double ... pur) {
int a = purchases.length;
purchases = Arrays.copyOf(purchases, purchases.length + pur.length);
for (int i = 0; i < pur.length; i++) {
purchases[a + i] = pur[i];
}
}
However, DO NOT use arrays and resize it manually. If you need to insert unknown number of items into a collection, use dynamic-size collections like java.util.List or java.util.ArrayList.
Is this the right way of assigning each column in my data file to a particular variable?
public static void main(String[] args) {
//specifying the path to file
String datafile = " C:\\Users\\rez\\Desktop\\sol_2.mcmc";
//reading the file
double[][] mydata = FileReadingTools.getDoubleArray(datafile);
double P_0; //days
double M_0; // in days
double e_0;
double w_0 = Math.toRadians(0);
double[][] list = new double[3000][50];
for (int sol = 0; sol < 3000; sol++) {
list[sol][0] = P_0;
list[sol][2] = M_0;
list[sol][3] = e_0;
list[sol][4] = w_0;
System.out.println(P_0 + " " + M_0);
}
I believe you have swapped the left and right with your variable assignments. You want to assign the values from the array. Also, please use more descriptive variable names. I think you wanted something like,
for (int sol = 0; sol < mydata.length; sol++) {
P_0 = mydata[sol][0]; // mydata v-- as noted in the comments. ---v
M_0 = mydata[sol][2];
e_0 = mydata[sol][3];
w_0 = mydata[sol][4];
Alternatively, you could use printf and access the array directly with something like
System.out.printf("%.2f %.2f", mydata[sol][0], mydata[sol][2]);
I have an array of objects of my class "Points" and I want to put them on a JSONArray, previusly cast to JSONObject, but I have one problem I can't solve, I can't put my points[] on the JSONObject and I don't know how to do it. I put the code to explain it better.
Principal code:
JSONArray jsPoints = new JSONArray();
for(int i = 0; i < points.length; i++)
{
JSONObject js = new JSONObject(points[i]);
jsPoints.put(js);
}
Point class:
public class Point {
String _id;
String _comment;
String _calification;
String _coords;
int _X;
int _Y;
public Point(String id, String comment, String calification, String coords, int x, int y)
{
_id = id;
_comment = comment;
_calification = calification;
_coords = coords;
_X = x;
_Y = y;
}
}
Introducing values into my class:
private void createPoints()
{
points = new Point[drawedInterestPoints.size() / 2];
int j = 0;
for(int i = 0; i < drawedInterestPoints.size() - 1; i++)
{
if(i % 2 == 0)
{
points[j] = new Point(pointType.get(i),comments.get(i),calification.get(i),GPScoords.get(i),drawedInterestPoints.get(i),drawedInterestPoints.get(i + 1));
j++;
}
}
}
Anyone can tall me what I have to do to put each of my points[] in a JSONObject and then in a JSONArray? Thanks!
Try with GSON. Do this:
Gson gson = new Gson();
final MyClass myClass = gson.fromJson(jsonString, MyClass.class);
Hope this helps.. :)
you can not directly cast JSONArray to Points
what you can do something like following
get json as a string
de-serialize json to Point using jackson(ObjectMapper)
In your code
JSONObject js = new JSONObject(points[i]);
make no sense; You should put every items of points[] as tag in the jsObject and then insert it in a JsonArray
Try this:
public void jsonAsStr() {
JSONObject mJsonObj = new JSONObject();
try {
mJsonObj.put("tag1", true);
mJsonObj.put("tag2", 120);
mJsonObj.put("tag3", "Demo");
JSONArray jsPoints = new JSONArray();
jsPoints.put(mJsonObj);
} catch (JSONException e) {
e.printStackTrace();
}
}
You can do this way using gson
Gson gson = new Gson();
Point point = new Point("", "", "", "", 1, 2);
String json = gson.toJson(point);
I am having a little trouble with my code. I have a hash map which has data. I want to get that data from the hash table and so far so good everything was working properly until I tried to get the coordinates of a point. I have made a class called "Segments" it contains a string "name" and an array of Doubles (longitude latitude). It is supposed to fill the variables with data from the hash table. In debug mode I saw the elements the longitude and latitude but it doesn't put them into the arrays I have specified and it prints out an error:
"ClassCastException: java.lang.Object[] cannot be cast to java.lang.Double"
Here is my code.
public class Segments
{
public String name;
public double[] latitude;
public double[] longitude;
public void Read(HashMap<String,Object> segment)
{
this.name = (String) segment.get("name");
Object[] coord = (Object[]) segment.get("coordinates");
try
{
for(int i = 0; i < coord.length; i++)
{
latitude[i] = (Double)coord[0];
longitude[i] = (Double)coord[1];
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
Can you tell me what am I doing wrong and how to fix my code?
I think the main issue is that your coord array doesn't contain coordinates but rather an array of array of coordinates. Therefore the correct way to address this would be:
for(int i = 0; i < coord.length; i++)
{
latitude[i] = (Double)coord[i][0];
longitude[i] = (Double)coord[i][1];
}
Notice the second-level array inside the loop.
EDIT: You may need to add an explicit cast to coord[i]. Try these - one of them might work for you:
latitude[i] = ((Double[])coord[i])[0];
longitude[i] = ((Double[])coord[i])[1];
or
latitude[i] = ((double[])coord[i])[0];
longitude[i] = ((double[])coord[i])[1];
or
latitude[i] = (Double)((Object[])coord[i])[0];
longitude[i] = (Double)((Object[])coord[i])[1];
You are trying to cast a primitive object to Object.
You can try to change your values do Double or cast to double[]
Also this is a very common mistake, remember that all primitives doesn't extend Object in Java
Try this code:
public class Segments
{
public String name;
public Double[] latitude;
public Double[] longitude;
public void Read(HashMap<String,Object> segment)
{
this.name = (String) segment.get("name");
Double[] coord = (Double[]) segment.get("coordinates");
try
{
for(int i = 0; i < coord.length; i++)
{
latitude[i] = coord[0];
longitude[i] = coord[1];
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
Guys I found the solution and of course thank you for your help you pointed me to the right way. Sop the solution was that i had to declare the size of the array and the arrays (latitude, longitude) must be "double" not "Double" and so to fill the arrays (latitude, longitude) the code must look like:
public class Segments
{
public String name;
public double[] latitude;
public double[] longitude;
public void Read(HashMap<String,Object> segment)
{
this.name = (String) segment.get("name");
Object[] coord = (Object[]) segment.get("coordinates");
//Object[] coord2 = new Object[coord.length];
latitude = new double[coord.length];
longitude = new double[coord.length];
try
{
for(int i = 0; i < coord.length; i++)
{
latitude[i] = (Double)((Object[])coord[i])[0];
longitude[i] = (Double)((Object[])coord[i])[1];
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
I have a JSON file which looks like the following:
{"posts":[{"Latitude":"53.38246685","lontitude":"-6.41501535"},
{"Latitude":"53.4062787","lontitude":"-6.3767205"}]}
and I can get the first set of latitude and lontitude co-ordinates by doing the following:
JSONObject o = new JSONObject(s);
JSONArray a = o.getJSONArray("posts");
o = a.getJSONObject(0);
lat = (int) (o.getDouble("Latitude")* 1E6);
lng = (int) (o.getDouble("lontitude")* 1E6);
Does anyone have an idea of how to get all the latitude and lontitude values ?
Any help would be much appreciated.
Create ArrayLists for the results:
JSONObject o = new JSONObject(s);
JSONArray a = o.getJSONArray("posts");
int arrSize = a.length();
List<Integer> lat = new ArrayList<Integer>(arrSize);
List<Integer> lon = new ArrayList<Integer>(arrSize);
for (int i = 0; i < arrSize; ++i) {
o = a.getJSONObject(i);
lat.add((int) (o.getDouble("Latitude")* 1E6));
lon.add((int) (o.getDouble("lontitude")* 1E6));
}
This will cover any array size, even if there are more than two values.
In the below code, I am using Gson for converting JSON string into java object because GSON can use the Object definition to directly create an object of the desired type.
String json_string = {"posts":[{"Latitude":"53.38246685","lontitude":"-6.41501535"},{"Latitude":"53.4062787","lontitude":"-6.3767205"}]}
JsonObject out = new JsonObject();
out = new JsonParser().parse(json_string).getAsJsonObject();
JsonArray listJsonArray = new JsonArray();
listJsonArray = out.get("posts").getAsJsonArray();
Gson gson = new Gson();
Type listType = new TypeToken<Collection<Info>>() { }.getType();
private Collection<Info> infoList;
infoList = (Collection<Info>) gson.fromJson(listJsonArray, listType);
List<Info> result = new ArrayList<>(infoList);
Double lat,long;
if (result.size() > 0) {
for (int j = 0; j < result.size(); j++) {
lat = result.get(j).getLatitude();
long = result.get(j).getlongitude();
}
//Generic Class
public class Info {
#SerializedName("Latitude")
private Double Latitude;
#SerializedName("longitude")
private Double longitude;
public Double getLatitude() { return Latitude; }
public Double getlongitude() {return longitude;}
public void setMac(Double Latitude) {
this.Latitude = Latitude;
}
public void setType(Double longitude) {
this.longitude = longitude;
}
}
Here the result is obtained in lat and long variable.
Trusting my memory and my common sense... have you tried:
o = a.getJSONObject(1);
Look here