how to get array of objects from server - java

I'm trying to have a list of objects from a server. But I don't know how to do it exactly and at least print it in System.out.print
server sends data like that:
[
{
"userId": "15",
"routeId": "10",
"driverId": "2",
"text": "ytf",
"timestamp": "2018-05-25 13:04:01"
},
{
"userId": "15",
"routeId": "33",
"driverId": "2",
"text": "asd",
"timestamp": "2018-05-25 13:07:40"
}
]
And model:
https://pastebin.com/52mc5Gmw
https://pastebin.com/DnUTtkPC
Controller: https://pastebin.com/ucJFFJyy
And the API:
#GET("getReviews.php")
Call<List<reviewResult>> getReview();

You can use JSONArray for parse the array, and JSONObject for get each object of the array
Edit Add a example
JSONArray jsonArray = new JSONArray(response);
for(int i=0; i<jsonArray.length();i++)
{
JSONObject object = jsonArray.getJSONObject(i);
System.out.print(object);
}

From your code, looks like the expected return type should be List of reviewResponse objects. You should change the API to:
Call<List<reviewResponse>> getReview();
From there it's obvious how to retrieve the data you ask

Related

Converting a normal String to JSON in java

i've been searching a lot for a way to convert a normal String, not an Array, and i'm stuck in my code. I've programmed an API that return me the following json
[{
"Id": "6d052279342d66d1ae4d4a84da0f98b80313277a3faeca4d7e822076c9dd4316",
"Names": ["/elegant_bartik"],
"Image": "alpine",
"ImageID": "sha256:3fd9065eaf02feaf94d68376da52541925650b81698c53c6824d92ff63f98353",
"Command": "/bin/sh",
"Created": 1525954440,
"Ports": [],
"Labels": {},
"State": "running",
"Status": "Up About an hour",
"HostConfig": {
"NetworkMode": "default"
},
"NetworkSettings": {
"Networks": {
"bridge": {
"IPAMConfig": null,
"Links": null,
"Aliases": null,
"NetworkID": "430ff6d43b361b0a2f45046c575862ca4785216a0242e72d145c269f3ef326df",
"EndpointID": "a7a2012d7841af6b5b76e24f57b13a5057252b511e8dbfb48e74aa1cc19e30b4",
"Gateway": "172.17.0.1",
"IPAddress": "172.17.0.2",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "02:42:ac:11:00:02",
"DriverOpts": null
}
}
},
"Mounts": []
}]
The problem is, I need to put it into an JSONObject, is there any function or sequence of functions that could do that? Or do I need to break the whole String?
I've tried JSONParse, Gson(from Google) and a lot more, but none of then works.
Thanks!
The JSON you have posted is an array (denoted by []) containing a single object (denoted by {})
You will first need to parse the JSON into an array, for example (using GSON):
JsonArray arr = new Gson().fromJson(string, JsonArray.class)
And then you can access the first object in the array:
JsonElement ele = arr.get(0);
First, the json array string looks okay. you will have to read it as a jsonArray, then loop through each getting the jsonObjects.
JSONArray jsonArray = new JSONArray(readlocationFeed);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
}
I hope this helps.
That's a JSONArray. You first need to get the root json array. Then you can get the first object from that.

create a JSON file in java with array

I use JSON-simple-1.1.1 and I want to create a JSON file like this:
{
"data": [
[
"1",
"YES",
"sp_1",
"1",
"xxx"
],
[
"2",
"NO",
"sp_2",
"2",
"yyyy"
],
[
"3",
"YES",
"sp_3",
"2",
"zzzz"
]
]
}
I try to use JSONObject and JSONArray but I cannot resolve how to create a multi array like above
A little helper makes life easier:
public static JSONArray jsonArray(Object... values) {
JSONArray arr = new JSONArray();
arr.addAll(Arrays.asList(values));
return arr;
}
Then:
JSONObject obj = new JSONObject();
obj.put("data", jsonArray(jsonArray("1", "YES", "sp_1", "1", "xxx"),
jsonArray("2", "NO" , "sp_2", "2", "yyyy"),
jsonArray("3", "YES", "sp_3", "2", "zzzz")));
System.out.println(obj.toJSONString());
Output
{"data":[["1","YES","sp_1","1","xxx"],["2","NO","sp_2","2","yyyy"],["3","YES","sp_3","2","zzzz"]]}
My Questions is bad write. I don't explain that read row from database and for that I don't know how many row found. the inside array is dinamic.
With Andreas help i found this solution:
public static JSONArray jsonArray(Object... values) {
JSONArray arr = new JSONArray();
arr.addAll(Arrays.asList(values));
return arr;
}
then:
JSONObject jo = new JSONObject();
JSONArray ja = new JSONArray();
// loop to database row. To simplify code example write some database row found...
ja.add(jsonArray("1", "YES", "sp_1", "1", "xxx"));
ja.add(jsonArray("2", "YES", "sp_1", "1", "xxx"));
ja.add(jsonArray("3", "YES", "sp_1", "1", "xxx"));
jo.put("data", ja );
System.out.print(jo);
Output:
{"data":[["1","YES","sp_1","1","xxx"],["2","YES","sp_1","1","xxx"],["3","YES","sp_1","1","xxx"]]}
Thank to all and sorry for my not clear question.

How do I convert a list represented as a string to a list?

I am building an Android application which reads from themoviedb.org.
What I am trying to do is have the user enter a movie title and use that title to find its id.
When I run the query to search for movies, I get a response like:
{
"page": 1,
"results": [
{
"poster_path": "aaaaa.jpg",
"id": "11",
"description": "MovieDescription"
},
{
"poster_path": "bbbbb.jpg",
"id": "12",
"description": "MovieDescription2"
},
{
"poster_path": "ccccc.jpg",
"id": "13",
"description": "MovieDescription"
}
]
}
Using the Maven JSON library, I can fetch the results key as a string using json.get("results").
returning:
[
{
"poster_path": "aaaaa.jpg",
"id": "11",
"description": "MovieDescription"
},
{
"poster_path": "bbbbb.jpg",
"id": "12",
"description": "MovieDescription2"
},
{
"poster_path": "ccccc.jpg",
"id": "13",
"description": "MovieDescription"
}
]
But I want to convert the first of these results to another JSONObject so that I can get the movie's id from the first result.
I'm thinking that the way to do this is to convert the results value to a list of JSONObject and then use the json.get("id") method on the first object in the list. But I do not know how to do this conversion.
Any help would be appreciated.
You can use JSONObject.getJSONArray to get the result directly as a JSON Array:
JSONArray results = json.getJSONArray("results") // Get results as JSON Array
JSONObject first = results.getJSONObject(0) // Get first object as JSON Object
See: JSONObject#getJSONArray(String)

JSON: Get list of JSON Objects

In java how can I pull out the JSON objects enclosed in the "{}"?
I have tried:
JSONObject obj = new JSONObject(jstring);
obj.getJSONArray("fileName");
But it only return the first object. How do I get a list with both objects?
JSON:
[
{
"fileName": [
"file1"
],
"date": [
"8/25/2015 0:00"
],
"time": [
"7/16/2009 16:51"
],
"id": "1",
"version_": 1
},
{
"fileName": [
"file1"
],
"date": [
"8/25/2015 0:00"
],
"time": [
"7/16/2009 16:51"
],
"id": "1",
"version_": 1
}
]
Your root JSON is an Array, so first create a JSONArray from your String.
Do this:
JSONArray arr = new JSONArray(jstring);
for (int i = 0; i < arr.length(); i++) { // Walk through the Array.
JSONObject obj = arr.getJSONObject(i);
JSONArray arr2 = obj.getJSONArray("fileName");
// Do whatever.
}
For more info, please refer to the docs on JSONArray and JSONObject.
You have to directly construct JSONArray from JSON string in this case.
JSONArray arr = new JSONArray(jstring);
JSONArray jsonArray = new JSONArray(jstring);

how to retrieve JSON object from the JSON array

I am having the below JSON. Inside this JSON I am having "ticketDetails" as JSON array. From this array I want to retrieve the value of ticketPrice inside the json object "amount". How can I do that?
{
"ticketDetails": [{
"seq": 1,
"qty": 2,
"amount": {
"ticketPrice": 120,
"bookingFee": 50
},
"session": {
"id": 1001,
"date": "2013, 9, 15",
"time": "1300"
},
"venue": {
"id": "MTRG",
"name": "Adlabs Manipur",
"companyCode": "ADLB"
},
"event": {
"id": "ET00000001123",
"name": "Chennai Express",
"producerCode": "YRF"
},
"category": {
"ttypeCode": "00012",
"areaCatCode": "2414",
"type": "Gold",
"price": 270
}
}]
}
Any suggestion will helpful...
Below is the sample code for retrieving the ticketPrice from the given JSONObject:
JSONObject objData = (JSONObject)JSONSerializer.toJSON(data);
JSONArray objTicketDetailsJsonArr = objData.getJSONArray("ticketDetails");
for(int nSize=0; nSize < objTicketDetailsJsonArr.size(); nSize++){
String ticketPrice = "";
ticketPrice = objTicketDetailsJsonArr.getString("ticketPrice");
}
Below are the imports for the above code:
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
source of JAR: http://json-lib.sourceforge.net/
you store your data within a variable
data = {...}
then you access it this way:
data.ticketDetails[0].amount.ticketPrice
if the ticketDetails have more than one element
you can loop over the ticketDetails array and store all the ticketPrice values within an other array, ticketPriceArray
the following would work fine in JavaScript:
var ticketPriceArray = data.ticketDetails.map(function(k){
return k.amount.ticketPrice;
});
if you are using another programming language a general loop would work fine also
for ( i; i< ticketDetails.length ; i++){
ticketPriceArray[i] = data.ticketDetails.amount.ticketPrice[i];
}
For Java check this tutorial:
http://answers.oreilly.com/topic/257-how-to-parse-json-in-java/
you can try this code:
JsonObject transactiondata = (JsonObject)Offer.get("transData");
JsonObject ticketdata = (JsonObject)transactiondata.get("tickets");
JsonObject offerData = (JsonObject)Offer.get("offerData");
JsonObject offerData1 = (JsonObject)offerData.get("offerconfig");
JsonArray jsonarr= (JsonArray)ticketdata.get("ticketDetails");
double ticketPrice = Double.parseDouble(jsonarr.get(0).getAsJsonObject().get("amount").getAsJsonObject().get("ticketPrice").getAsString());
System.out.println("ticketPrice:"+ticketPrice);

Categories