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);
Related
I have a JSONArray as below,
JSONArray dataArray = new JSONArray();
dataArray = [
{
"name": "name1",
"row": 1,
"value": 20
},
{
"name": "name2",
"row": 1,
"value": 10
},
{
"name": "name3",
"row": 2,
"value": 10
},
{
"name": "name4",
"row": 3,
"value": 30
},
{
"name": "name5",
"row": 3,
"value": 10
}
]
I need to compare the row attribute, if same, need to compare value attribute and sort the object in the array.
Tried with Java comparator, but couldn't make it work. Can somebody please help?
for(int i = 0; i < dataArray.size(); i++) {
elementList.add((JSONObject) dataArray.get(i));
}
Long row1 = null;
for (JSONObject obj : elementList) {
if(row1 == null) {
row1 = (Long) ((JSONObject) obj.get("row"));
}
else {
Long row2 = (Long) ((JSONObject) obj.get("row"));
if(row2 == row1) {
//call the comparator, but how to pass two objects?
}
row1 = row2;
}
}
It would be easy to extend this answer to match your scenario
But instead of
return valA.compareTo(valB);
you should do
int comp = valA.compareTo(valB);
if (comp == 0){
String valC = (String) a.get(KEY_NAME2);
String valD = (String) b.get(KEY_NAME2);
return valC.compareTo(valD);
} else {
return comp;
}
So it should be the following.
JSONArray sortedJsonArray = new JSONArray();
List<JSONObject> jsonValues = new ArrayList<JSONObject>();
for (int i = 0; i < dataArray.length(); i++) { // <---- dataArray is the input that you have
jsonValues.add(dataArray.getJSONObject(i));
}
Collections.sort( jsonValues, new Comparator<JSONObject>() {
//You can change "Name" with "ID" if you want to sort by ID
private static final String KEY_NAME1 = "row";
private static final String KEY_NAME2 = "value";
#Override
public int compare(JSONObject a, JSONObject b) {
String valA = new String();
String valB = new String();
try {
valA = (String) a.get(KEY_NAME1);
valB = (String) b.get(KEY_NAME1);
}
catch (JSONException e) {
//do something
}
int comp = valA.compareTo(valB);
if (comp == 0){
String valC = (String) a.get(KEY_NAME2);
String valD = (String) b.get(KEY_NAME2);
return valC.compareTo(valD);
} else {
return comp;
}
}
});
Edit: changed into KEY_NAME1 = "row"; to match the new question requirement
A simpler approach here:
You could convert your JSON string to List<YourObject> by using Jackson's ObjectMapper
List<YourObject> list = objectMapper.readValue(json, new TypeReference<List<YourObject>>(){});
Then use Collections.sort and Comparator to sort this list. You can also implement a custom Comparator to sort a list by multiple attributes depending on your situation.
list.sort(Comparator.comparing(YourObject::getRow)
.thenComparing(YourObject::getValue));
Let's assume you deserialize your json data into objects like
public class DataRow {
private String name;
private int row;
private int value;
// Getter, Setter, Constructor what ever needed
}
Then you can work with a list and stream like:
List<DataRow> datarows = //... read data from json
List<DataRow> sorted = datarows.stream()
.sorted(Comparator.comparing(DataRow::getRow).thenComparingInt(DataRow::getValue)).toList();
There is a class called PageInfo which is like this:
I assume the max size of arrays is 5.
public static class PageInfo {
String username;
PageInfo[] followings;
Post posts[];
PageInfo (String username,PageInfo[] followings,Post[] posts) {
this.username = username;
this.followings = followings;
this.posts = posts;
}
public int getPostLength () {
int cnt = 0;
for (int i = 0; i < 5; i++) {
if (posts[i] != null )
cnt++;
}
return cnt;
}
public int getFollowingLength () {
int cnt = 0;
for (int i = 0; i < 5; i++) {
if (followings[i] != null )
cnt++;
}
return cnt;
}
}
and there is a Post class like:
public static class Post {
String cation;
int id;
PageInfo[] usersLiked;
Post (String caption, int id, PageInfo[] usersLiked) {
this.cation = caption;
this.id = id;
this.usersLiked = usersLiked;
}
}
I want to declare a user with constructor like:
PageInfo[] allusers = new PageInfo[5];
allusers[0] = new PageInfo("John", "54321", new PageInfo[5], new Post[5]);
allusers[0].followings[0] = allusers[1];
allusers[0].posts[0] = new Post("John Post", 100, new PageInfo[5]);
The "getPostLength" works well.
but when "GetFollowingLength" returns me 0. why? and how to fix it?
how can i add "followings" to the allusers[x] later in the project?
It seems that "followings" hasn't been initialized yet and the're still Null. how can i properly initalize them?
I think what you're missing is that an array is initialized with null values when you do "new PageInfo[5]" or something similar. So followings is initialized as an empty array (all values null). Same with allusers. So "allusers[0].followings[0] = allusers[1];" does not do anything here. It just sets the value to null, which it already is.
I don't know what exactly you want to achieve, so I'm not sure how you could improve your code. One way could be to initialize an array like this:
Foo array = new Foo[42];
for(int i=0; i<array.length; i++
{
array[i] = new Foo();
}
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));
}
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