I'm having trouble parsing a json response. Its created via php and sent back to my phone via http as json.
It is an array with 3 arrays in it so...
$arr = array();
Then I search my mysql database for specific IDs relating to the query, usually about 3 results are returned with unique ids as the array index.. like this
$sql = mysql_query("Select from so and so");
while($row = mysql_fetch_assoc($sql)){
$arr[$row["ID"]] = $row;
}
print(json_encode($arr));
so now in my android (java) code I'm trying to convert the response to a json object and then parse it with
json_object.getString("FirstName")
for all 3 of the first names returned but its crashing. So i am guess I need to parse out the 3 individual arrays first which is where I am stuck.
-The question is how do I sort out the arrays returned within this one object. Each of them have the same keys, but different values
-crashing wasnt a good choice in terms, what I should have said is it cant find the value I am searching for when I use the getString method, here is the return
Agree with the comments above, would need more details.
But if you're getting back a properly formatted JSON response and it's an Array, you could always do something like ...
JSONArray results = new JSONArray(<json response string>);
for (int i=0; i<results.length(); i++) {
JSONObject obj = results.getJSONObject(i);
}
And documentation for your reference:
http://developer.android.com/reference/org/json/JSONArray.html
Related
I am developing an app that communicates with Database, to retrieve values. I am using PHP for the Backend, and developing on Android Studio, using the Volley Library.
My problem is, the values that I need to send are multiple records of a table, each with four columns, for example name, age, department, and country. I am using JSON to encode these values, but I need help with how to proceed. Should I use JSON encoded 2D Arrays? if so, how to make use PHP to construct this array, as there can be variable numbers of rows.
Also, How to parse that JSON Object/Array in Android (Java)?
As of now, this is my progress:
JSON Output in browser:
{"name0":"ABC","age0":"25","department0":"Medical","country0":"XYZ","name1":"DEF","age1":"26","department1":"Engg.","country1":"XYZ"}
Here, I named each "key" of JSON using a Loop in PHP, and encoded as JSON Object. But Having Difficulty in displaying this in Android. I have used a XML layout with 4 textviews, and LISTVIEW in the main Activity XML File.
I would suggest a different json structure for encoding. Yours will get messy pretty quick if there are a lot of records. For example you would have name0, name1, ... nameN. It would be better to make an array like so:
[
{
"name" : "ABC",
"age" : 25,
"department" : "Medical",
"country" : "XYZ"
},
{
...
}
]
Notice that there are no indices concatenated to your keys. You can get the index based on the json object node's position in the array if you need it.
As for parsing it in Android, you can refer to the documentation. There is a Json parser that comes with the SDK so all you need to do is read in your string as a json array and iterate over its object nodes as needed.
For example
String jsonResponse = " ... "; // whatever the php backend gives you when you make a call to the endpoint
JSONArray arr = new JSONArray(jsonResponse);
for (int i=0; i<arr.length(); i++) {
JSONObject obj = arr.get(i);
String name = obj.getString("name");
...
}
The webservice: http://services.groupkt.com/country/search?text=lands has 16 records returned from a GET request. In the records, there is a parameter called 'name'. So, there are 16 names and each name has a unique value (country). My intention is to list all the 16 values of the 'name'parameter using java and the RESTassured library. I tried this:
Response response = RestAssured.get("http://services.groupkt.com/country/search?text=lands").andReturn();
String json = response.getBody().asString();
JsonPath jp = new JsonPath(json);
List<String> ls = from(response).getList("RestResponse.result.name");// The 'from' text displays an error
An error was seen on the 'from' text and it says: The method from(String) in the type RestTest is not applicable for the arguments (Response). I am not sure how to rectify this. Is there a simple way to create a list of all the values of the 'name' parameter?
Try replacing from(response) to from(jp). That should take care of the error you are getting.
The Response class (which is what the get() method returns) also supports jsonPath, so you could also refactor it to something like this:
List names= get("http://services.groupkt.com/country/search?text=lands").jsonPath().getList("RestResponse.result.name");
I have written a java servlet to deal with http get request.I know ,the common format of get request is like this:http://IP_ADDRESS:8080/test?name="jack"&value="shit.
But now ,I have a list of values to transfer,such as an user id list[1,2,3,4].So ,my question is ,how should I write my http get request to express this?And in java servets doGet(),can I use request.getParameterValues to get such an array?
if you are using GET method your url should be looking like that :
http://IP_ADDRESS:8080/test?list=1&list=2&list=3
for retrieving it:
String[] arrlist=request.getParameterValues('list');
your array will be filled with separated values:
//["1","2","3"]
UPDATE : if to write it list[] or list?
when you retrieving your list parameters it wouldn't be parsed as array but as a series of String which will be grouped later on into an array.
Which means even if you write it list[]=1&list[]=2&list[]=3, list[=1&list[=2&list[=3, list*=1&list*=2&list*=3 or list=1&list=2&list=3 it would always be giving you the same answer whether you retrieve it as
request.getParameterValues('list[]') //["1","2","3"]
request.getParameterValues('list[') //["1","2","3"]
request.getParameterValues('list*') //["1","2","3"]
request.getParameterValues('list') //["1","2","3"]
While ,the http request format should be like this:localhost:8080/test?list[]=1&list[]=2&list[]=3
Maybe too simple, but what about repeat parameters name?
http://IP_ADDRESS:8080/test?userId=1&userId=2&userId=3
While searching using java api in elaticsearch, I would like to retrieve only one column.
Currently when I query using the Java API it returns the whole record like this: [{_id=123-456-7890, name=Wonder Woman, gender=FEMALE}, {_id=777-990-7890, name=Cat Woman, gender=FEMALE}]
The record above correctly matches the search condition shown in th . As shown in the code below:
List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
SearchRequestBuilder srb = client.prepareSearch("heros")
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH);
MatchQueryBuilder mqb;
mqb = QueryBuilders.matchQuery("name", "Woman");
srb.setQuery(mqb);
SearchResponse response = srb.execute().actionGet();
long totalHitCount = response.getHits().getTotalHits();
System.out.println(response.getHits().getTotalHits());
for (SearchHit hit : response.getHits()) {
result.add(hit.getSource());
}
System.out.println(result);
I want only one column to be returned. If I search for name I just want the full names back in a list: "Wonder Woman", "Cat Woman" only not the whole json record for each of them. If you think I need to iterate over the result list of maps in java please propose an example of how to do that in this case.
You can specify the fields to be returned from a search, per documentation. This can be set via SearchRequestBuilder.addFields(String... fields), ie:
SearchRequestBuilder srb = client.prepareSearch("heros")
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.addFields("name");
Better combine both:
use .addFields("name") to tell ES that it needs to return only this
column
use hit.field("name").getValue().toString() to get the result
It is important to use .addFields when you don't need the whole document, but the specific field/s as it will lower the overhead and the network traffic
I figured it out.
List<String> valuesList= new ArrayList<String>();
for (SearchHit hit : response.getHits()) {
result.add(hit.getSource());
valuesList.add(hit.getSource().get("name").toString());
}
The other solutions didn't work for me, hit.getSource() was returning null. Maybe they are deprecated? Not sure. But here was my solution, which FYI can speed things up considerably if you are only getting one field and you are getting lots of results.
Use addFields(Strings) on your SearchRequestBuilder as mentioned, but then when you are getting the values you need to use:
hit.getFields().get( fieldName ).getValue()
or
hit.getFields().get( fieldName ).getValues()
to get a single value or a list of values depending on the field.
Update: I should have mentioned this right off the bat: I first considered a Java/JSON mapping framework, but my manager does not want me adding any more dependencies to the project, so that is out as an option. The JSON-Java jar is already on our classpath, so I could use that, but still not seeing the forest through the trees on how it could be used.
My Java program is being handed JSON of the following form (althought the values will change all the time):
{"order":{"booze":"1","handled":"0","credits":"0.6",
"execute":0,"available":["299258"],"approved":[],
"blizzard":"143030","reviewable":["930932","283982","782821"],
"units":"6","pending":["298233","329449"],"hobbit":"blasphemy"}}
I'm looking for the easiest, efficient, surefire way of cherry-picking specific values out of this JSON string and aggregating them into a List<Long>.
Specifically, I'm looking to extract-and-aggregate all of the "ids", that is, all the numeric values that you see for the available, approved, reviewable and pending fields. Each of these fields is an array of 0+ "ids". So, in the example above, we see the following breakdown of ids:
available: has 1 id (299258)
approved: has 0 ids
reviewable: has 3 ids (930932, 283982, 782821)
pending: has 2 ids (298233, 329449)
I need some Java code to run and produce a List<Long> with all 6 of these extracted ids, in no particular order. The ids just need to make it into the list.
This feels like an incredibly complex, convoluded regex, and I'm not even sure where too begin. Any help at all is enormously appreciated. Thanks in advance.
The easiest way IMO is use a json library such as gson, jackson, json.org, etc, parse de JSON into an object and create a new List<Long> with the values of the properties you need.
Pseudocode with gson:
class Order {
long[] available;
long[] approved;
...
}
Order order = gson.fromJson("{ your json goes here }", Order.class);
List<Long> result = new ArrayList<Long>();
result.add(order.getAvailable());
result.add(order.getApproved());
...
Pseudocode with json.org/java:
JSONObject myobject = new JSONObject("{ your json goes here"});
JSONObject order = myobject.getJSONObject("order");
List<Long> result = new ArrayList<Long>();
for (int i=0; i<order.getJSONArray("approved").length(); i++) {
Long value = order.getJSONArray("approved").getLong(i);
result.add(value);
}
...