Related
Here's what im trying to do. There are two arrays that i want to retrieve from my mysql database. These two arrays are echoed separately:
echo json_encode(array("friendrequest"=>$friendrequest));
echo json_encode(array("friendresult"=>$friendresult));
This is the code i use to process the resulting string:
public void onResponse(String response) {
Log.d("Response", response);
try {
JSONObject jsonObj = new JSONObject(response);
JSONArray ja_data = jsonObj.getJSONArray("friendresult");
String[] from = {
"first_name",
"anytimer_count",
"relationship_status"
}; //string array
int[] to = {
R.id.textListView1,
R.id.textListView2,
R.id.textListView3
}; //int array of views id's
JSONArrayAdapter arrayListAdapter = new JSONArrayAdapter(MyFriendsActivity.this, ja_data, R.layout.custom_list_items, from, to);
list.setAdapter(arrayListAdapter);
JSONArray ja_requests = jsonObj.getJSONArray("friendrequest");
int ja_lengths = ja_requests.length();
Log.d("Response", Integer.toString(ja_lengths));
} catch (JSONException e) {
Log.e("MyFriendsActivity", "unexpected JSON exception", e);
}
Now, the logged reponse from line 2 in the processing code gives me the following:
Response =
{
"friendrequest": [
{
"first_name": "Tom",
"anytimer_count": "0",
"relationship_status": "0"
},
{
"first_name": "Bert",
"anytimer_count": "0",
"relationship_status": "0"
}
]
}{
"friendresult": [
{
"first_name": "Luuk",
"anytimer_count": "0",
"relationship_status": "1"
}
]
}
This is contains all the values that should be sent and is correct.
The problem is that my processing code is only able to recognize the array that is encoded first in the php script. Basically if i swap the position of the two lines of code in the php script, 'friendrequest' will contain values, while 'friendresult' does not and vice versa. What am i doing wrong here?
The error im getting:
org.json.JSONException: No value for friendresult
at
com.example.tomva.anytimereverywhere.MyFriendsActivity$3.onResponse(MyFriendsActivity.java:84)
Line 84 is the following line:
JSONArray ja_data = jsonObj.getJSONArray("friendresult");
You have to pass yours json in a array to be able to extract them all.
Shold be:
[
<?php
echo json_encode(array("friendrequest"=>$friendrequest));
echo ",";
echo json_encode(array("friendresult"=>$friendresult));
?>
]
Related answer
or you can use following
echo json_encode(array("friendrequest"=>$friendrequest,"friendresult"=>$friendresult));
Replace
echo json_encode(array("friendrequest"=>$friendrequest));
echo json_encode(array("friendresult"=>$friendresult));
With this
echo json_encode(array("friendrequest"=>$friendrequest,"friendresult"=>$friendresult));
Your Response JSON is not valid as it has missing ","
try to change your response from
{"friendrequest": [{"first_name":"Tom","anytimer_count":"0","relationship_status":"0"},{"first_name":"Bert","anytimer_count":"0","relationship_status":"0"}]} {"friendresult": [{"first_name":"Luuk","anytimer_count":"0","relationship_status":"1"}]}
To
[{
"friendrequest": [{
"first_name": "Tom",
"anytimer_count": "0",
"relationship_status": "0"
}, {
"first_name": "Bert",
"anytimer_count": "0",
"relationship_status": "0"
}]
}, {
"friendresult": [{
"first_name": "Luuk",
"anytimer_count": "0",
"relationship_status": "1"
}]
}]
Common Errors
Expecting 'STRING' - You probably have an extra comma at the end of
your collection. Something like { "a": "b", }
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[' -
You probably have an extra comma at the end of your list.
Something like: ["a", "b", ]
Enclosing your collection keys in quotes. Proper format for a
collection is { "key": "value" }
Make sure you follow JSON's syntax properly. For example, always
use double quotes, always quotify your keys, and remove all
callback functions
Here's my Java code in order to extract data from Adobe Analytics: (cloned from GitHub repository)
public static AnalyticsClient SecretAuthentication(String endpoint,String username,String password){
AnalyticsClient client = new AnalyticsClientBuilder()
.setEndpoint(endpoint)
.authenticateWithSecret(username, password)
.build();
return client;
}
public static void main(String[] args) throws IOException, InterruptedException{
AnalyticsClient client = SecretAuthentication("api.omniture.com","username","my_secret_pass");
ReportDescription desc = new ReportDescription();
String rsid="my_rs_id";
desc.setReportSuiteID(rsid);
desc.setDateFrom("2016-10-12"); // YYYY-MM-DD
desc.setDateTo("2016-10-13");
desc.setMetricIds("entries","orders","pageviews","visits","visitors");
String[] elements = new String[2];
elements[0]="prop3";
elements[1]="prop33";
desc.setElementIds(elements);
//Pass the description to the API queue method, which will start the process of preparing the report:
ReportMethods reportMethods = new ReportMethods(client);
int reportId = reportMethods.queue(desc);
System.out.println(reportId);
//The received integer is a report id, which can be used to receive the actual report using the get() method.
//Preparing report takes some time, and the get() method will throw an exception with appropriate message if the report is not ready yet.
//Following code runs the get() method in a loop, waiting until the report is ready:
ReportResponse response = null;
while (response == null) {
try {
response = reportMethods.get(reportId);
//System.out.println(response.toString());
} catch (ApiException e) {
System.out.println(e.toString());
Thread.sleep(3000);
continue;
}
}
List<ReportData> responseData = response.getReport().getData();
System.out.println("Is there data in the report? "+responseData.size());
for (int j = 0; j < responseData.size(); j++)
{
System.out.println(responseData.get(j).getName()+ " has :");
System.out.println(responseData.get(j).getCounts());
}
}
An example output of the last "for" statement is:
FR has :
[35732.0, 0.0, 115146.0, 36402.0, 32111.0]
The 5-sized vector includes the metric values ("entries","orders","pageviews","visits","visitors")
The "FR" (France) is the value of the first element (prop3) which is actually the "Country" variable.
The problem is that I have no information about the second element, prop33 (prop33 is "Device Type").
String[] elements = new String[2];
elements[0]="prop3";
elements[1]="prop33";
The most important is that Adobe seems to ignore the second element (prop33) and considers only the first one (prop3) for its search. I can prove this by changing the order of the two elements in elements array.
String[] elements = new String[2];
elements[0]="prop33";
elements[1]="prop3";
If I place prop33 first the output lines are different and Adobe responds as if prop33(Device Type) were the only criterion. For example:
iPhone has :
[47636.0, 6.0, 107440.0, 47729.0, 42330.0]
So, how can I send two or more elements as a matching criterion??
I figured it out. The "problem" has nothing to do with the parameter format!! The Adobe response follows the json format too. In order to see all response data you need to call the "getBreakdown()" method in order to discover the "lower" layers of the json response tree! In my attached code the "for" statement prints only data for the prop3 json element because this is the first layer of Adobe's response. If someone wants to see prop33 element should do the following:
for (int j = 0; j < responseData.size(); j++)
{
System.out.println(responseData.get(j).getName()+ " has :");
System.out.println(responseData.get(j).getCounts());
List<ReportData>reportData;
reportData = responseData.get(j).getBreakdown();//<---Here's what is needed!!
for (int i = 0; i < reportData.size(); i++)
{
System.out.println(" "+reportData.get(i).getName());
System.out.println(" "+reportData.get(i).getCounts());
}
System.out.println("===============================================");
}
In general you need one of the many and handy json reader java libraries to traverse the json tree!!
This isn't an answer more of a response to your last comment that's too long for a comment that should hopefully help you figure out what the problem is. Again disclaimer that I'm not an actual java coder so take that for what it's worth. But..
Firstly, just to be clear, you did try this, right?
desc.setElementIds("prop3", "prop33");
And you say that doesn't work? Because looking at setElementIds I see
public void setElementIds(String... elementIds) { .. }
My 5 minute understanding of java is String... is basically syntactic sugar for String[] (array) but it's to accept the strings as multiple arguments passed, not a single array of strings, so it looks to me that passing multiple args is indeed the way to go.
But overall you should check what is actually being sent to Adobe in the request. I expect the requirements are similar for the soap/xml version, but I don't know really know the soap/xml version so here's the JSON version. Based on what you posted (Report.Queue) JSON object payload hould look like this:
{
"reportDescription":{
"reportSuiteID":"my_rs_id",
"dateFrom":"2016-10-12",
"dateTo":"2016-10-13",
"metrics":[
{
"id":"entries"
},
{
"id":"orders"
},
{
"id":"pageviews"
},
{
"id":"visits"
},
{
"id":"visitors"
}
],
"elements":[
{
"id":"prop3"
},
{
"id":"prop33"
}
]
}
}
So check the http(s) request to make sure it looks like that (or soap/xml equiv).
And your (JSON) response (Report.Get) should look something like this:
{
"report":{
"type":"ranked",
"elements":[
{
"id":"prop3",
"name":"prop3 name here"
},
{
"id":"prop33",
"name":"prop33 name here"
}
],
"reportSuite":{
"id":"my_rs_id",
"name":"rsid name here"
},
"period":"Wed. 12 Oct. 2016 - Thu. 13 Oct. 2016",
"metrics":[
{
"id":"entries",
"name":"Entries",
"type":"number",
"decimals":0,
"latency":4599,
"current":false
},
{
"id":"orders",
"name":"Orders",
"type":"number",
"decimals":0,
"latency":4599,
"current":false
},
{
"id":"pageviews",
"name":"Page Views",
"type":"number",
"decimals":0,
"latency":4599,
"current":false
},
{
"id":"visits",
"name":"Visits",
"type":"number",
"decimals":0,
"latency":4599,
"current":false
},
{
"id":"visitors",
"name":"Visitors",
"type":"number",
"decimals":0,
"latency":4599,
"current":false
}
],
"data":[
{
"name":"<first prop3 value>",
"url":"",
"counts":[
"246944",
"0",
"494509",
"251168",
"200670"
],
"breakdown":[
{
"name":"<first breakdown prop33 value>",
"url":"",
"counts":[
"226556",
"0",
"460021",
"231637",
"184294"
]
},
{
"name":"<second breakdown prop33 value>",
"url":"",
"counts":[
"17058",
"0",
"23930",
"17628",
"15085"
]
} //, etc...
]
},
{
"name":"<second prop3 value>",
"url":"",
"counts":[
"246944",
"0",
"494509",
"251168",
"200670"
],
"breakdown":[
{
"name":"<first breakdown prop33 value>",
"url":"",
"counts":[
"226556",
"0",
"460021",
"231637",
"184294"
]
},
{
"name":"<second breakdown prop33 value>",
"url":"",
"counts":[
"17058",
"0",
"23930",
"17628",
"15085"
]
} //, etc...
]
} //,etc..
],
"totals":[
"253490",
"0",
"503495",
"253490",
"201190"
],
"version":"1.4.16.10"
},
"waitSeconds":0,
"runSeconds":0
}
Currently I am using netbeans IDE. I tried using other solution, but to no luck so far.
Problem is, i am facing errors when trying to read the Json file from google Chrome bookmarks file (C:\Users\Admin\AppData\Local\Google\Chrome\User Data\Default\Bookmarks)
p/s: although there is no file type written in the name of Bookmarks, its content have been known as JSON
This is the what inside the Bookmarks.json:
{
"checksum": "20fdfad51db6d3199f8a09c3220dd93b",
"roots": {
"bookmark_bar": {
"children": [ {
"date_added": "13124893413824227",
"id": "6",
"name": "YouTube",
"type": "url",
"url": "https://www.youtube.com/"
}, {
"date_added": "13124893435163243",
"id": "7",
"name": "Welcome to Facebook",
"type": "url",
"url": "https://www.facebook.com/"
} ],
"date_added": "13124893381424539",
"date_modified": "13124893435163243",
"id": "1",
"name": "Bookmarks bar",
"type": "folder"
},
"other": {
"children": [ ],
"date_added": "13124893381424547",
"date_modified": "0",
"id": "2",
"name": "Other bookmarks",
"type": "folder"
},
"synced": {
"children": [ ],
"date_added": "13124893381424550",
"date_modified": "0",
"id": "3",
"name": "Mobile bookmarks",
"type": "folder"
}
},
"version": 1
}
And here is my code (JsonParser.java):
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JsonParser{
private static String jsonFile = "C:\\Users\\Admin\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Bookmarks";
public static void main (String[] args) {
try {
FileReader reader = new FileReader (jsonFile); //access the file
JSONObject jsonObject = (JSONObject) new JSONParser().parse(reader);
String c =(String) jsonObject.get("checksum"); //place
// String r =(String) jsonObject.get("roots"); //place
// String r =(String) jsonObject.get("children"); //place
System.out.println("check: " + c);
//System.out.println("roots: " + r);
JSONArray lang = (JSONArray) jsonObject.get("roots");
for (int i=0; i<lang.size(); i++) {
System.out.println ("Url Name : " + lang.get(i)+"\n");
} //data in the array
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
For some reason when I run the code these are the errors I got:
check: 4d55f8a0888f7dd918a702eda2821ccd
Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray
at JsonParser.main(JsonParser.java:28)
C:\Users\Admin\Documents\NetBeansProjects\Keep-It\nbproject\build-impl.xml:1051: The following error occurred while executing this line:
C:\Users\Admin\Documents\NetBeansProjects\Keep-It\nbproject\build-impl.xml:805: Java returned: 1
BUILD FAILED (total time: 2 seconds)
As you can see, only checksum succeed in being read, but the roots failed and gave out these errors.
You should also notice that there are some codes I put as comments, those are things i tried but still got the errors.
I hope anyone can help me to get these things working.
Thank you very much for helping
Issue is , you cannot cast object to array like (JSONArray) jsonObject.get("roots"); you have to follow the structure so parse according to object and array as shown below
JSONObject jsonObject = (JSONObject) new JSONParser().parse(reader);
String checksum =jsonObject.optString("checksum");
// get root object
JSONObject root = jsonObject.getJSONObject("roots");
// get root bookmarks object from root
JSONObject bookmarks = root.getJSONObject("bookmark_bar");
// get root children array from bookmarks
JSONArray childrens = bookmarks.getJSONArray("children");
JSONObject temp ;
for (int i=0; i<childrens.size(); i++) {
// get object using index from childrens array
temp = childrens.getJSONObject(i);
// get url
String url = temp.optString("url");
}
as your structure follow
JObject => root
root JSONObject has : bookmark_bar JSONObject
bookmark_bar JSONObject has : children JSONArray
children JSONArray has JSONObject which further has String: url
roots is not a JSONArray but a JSONObject.
So what you have to do is
JSONObject lang = jsonObject.get("roots");
and then you have too loop through all keys in the object which should be:
bookmark_bar
other
synced
It seems to me like "roots" is not an array, but an object when looking at the JSON. "children" under "bookmark_bar" is an array however
I have the following HTTP JSON-response in Java, which represents a user object.
{
"account": "Kpatrick",
"firstname": "Patrick",
[
],
"instances":
[
{
"id": "packerer-pool",
"key": "packerer-pool123",
"userAccount": "kpatrick",
"firstname": "Patrick",
"lastname": "Schmidt",
}
],
"projects":
[
{
"id": "packerer-projectPool",
"projectKey": "projectPool-Pool",
"cqprojectName": "xxxxx",
},
{
"id": "packerer-secondproject",
"projectKey": "projectPool-Pool2",
"cqprojectName": "xxxx",
},
{
"id": "packerer-thirdproject",
"projectKey": "projectPool-Pool3",
"cqprojectName": "xxxx",
}
],
"clients":
[
],
"dbid": 76864576,
"version": 1,
"id": "dbpack21"
}
Now, I want to search a specific project with the help of the projectkey (for example "projectPool-Pool2"). After that, I want to delete the element completely. Because my target is to send a HTTP post-call without this project.
The result should be similar to below for my HTTP post-call:
{
"account": "Kpatrick",
"firstname": "Patrick",
[
],
"instances":
[
{
"id": "packerer-pool",
"key": "packerer-pool123",
"userAccount": "kpatrick",
"firstname": "Patrick",
"lastname": "Schmidt",
}
],
"projects":
[
{
"id": "packerer-projectPool",
"projectKey": "projectPool-Pool",
"cqprojectName": "xxxxx",
},
{
"id": "packerer-thirdproject",
"projectKey": "projectPool-Pool3",
"cqprojectName": "xxxx",
}
],
"clients":
[
],
"dbid": 76864576,
"version": 1,
"id": "dbpack21"
}
First i have parsed the response to a string.
private static String getContent(HttpResponse response) {
HttpEntity entity = response.getEntity();
if (entity == null) return null;
BufferedReader reader;
try {
reader = new BufferedReader(new InputStreamReader(entity.getContent()));
String line = reader.readLine();
reader.close();
return line;
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
And now i am trying to search the specific project, but i don't know how to continue.
String StringResponse = getContent(JsonResponse);
JSONObject jsonObject = new JSONObject(StringResponse);
JSONArray ProjectsArray= jsonObject.getJSONArray("projects");
Is that approach correct?
Best Regards!
Once you have your array, try something like...
// Array to store the indexes of the JSONArray to remove
ArrayList<Integer> indexesToRemove = new ArrayList<Integer>();
// Iterate through projects array, check the object at each position
// if it contains the string you want, add its index to the removal list
for (int i = 0; i < projectsArray.length; i++) {
JSONObject current = projectsArray.get(i);
if (current.get("projectKey") == "**DESIRED PROJECT KEY**") {
indexesToRemove.add(i);
}
}
Now you can iterate through your indexes to remove, and remove the corresponding object from the array with the JSONArrays remove method (not sure what it is called, the code above is from memory). Make sure to remove your items BACKWARDS, otherwise you will delete earlier items, which will change the indexes, resulting in your removing an incorrect item if you then remove another index.
// Going through the list backwards so we can remove the highest item each
//time without affecting the lower items
for (int i = indexesToRemove.size()-1; i>=0; i--) {
projectsArray.remove(indexesToRemove.get(i));
}
I have a JSON string and I am trying to retrieve information from it. Json String looks like this.
JSON STRING :
{
"information": {
"device": {
"id": 0
},
"user": {
"id": 0
},
"data": [
{
"datum": {
"id": "00GF001",
"history_id": "9992BH",
"name": "abc",
"marks": 57,
"class": "B",
"type": "Student"
}
},
{
"datum": {
"id": "72BA9585",
"history_id": "78NAH2",
"name": "ndnmanet",
"marks": 70,
"class": "B",
"type": "Student"
}
},
{
"datum": {
"id": "69AHH85",
"history_id": "NN00E3006",
"name": "kit",
"department": "EF003",
"class": "A",
"type": "Employee"
}
},
{
"datum": {
"id": "09HL543",
"history_id": "34QWFTA",
"name": "jeff",
"department": "BH004",
"class": "A1",
"type": "Employee_HR"
}
}
]
}
}
I am trying to access data JSONArray and respective Datum from it. I differentiated each datum as per type such as student, employee etc and push information in hashmap.
I successfully did it in javascript but in Java I am struggle abit.
When I am trying to access JSONArray it throws exception
try {
JSONObject data = new JSONObject(dataInfo);
// Log.d(TAG, "CHECK"+data.toString());
JSONObject info = data.optJSONObject("information");
if(info.getJSONArray("data").getString(0).equals("Student") > 0) //exception here
Log.d(TAG, "Data"+ data.getJSONArray("data").length()); //exception here too
for(int m = 0; m < data.length(); m++){
// for(int s = 0; s < data[m].ge)
}
} catch (JSONException j){
j.printStackTrace();
}
Any pointers to create hashmap respective type I have. Appreciated
If you're trying to access the type field of a datum object, you'll want something like this:
JSONObject data = new JSONObject(dataInfo); // get the entire JSON into an object
JSONObject info = data.getJSONObject("information"); // get the 'information' object
JSONArray dataArray = info.getJSONArray("data"); // get the 'data' array
for (int i = 0; i < dataArray.length(); i++) {
// foreach element in the 'data' array
JSONObject dataObj = dataArray.getJSONObject(i); // get the object from the array
JSONObject datum = dataObj.getJSONObject("datum"); // get the 'datum' object
String type = datum.getString("type"); // get the 'type' string
if ("Student".equals(type)) {
// do your processing for 'Student' here
}
}
Note that you'll have to deal with exception handling, bad data, etc. This code just shows you the basics of how to get at the data that you're looking for. I separated each individual step into its own line of code so that I could clearly comment what is happening at each step, but you could combine some of the steps into a single line of code if that is easier for you.
if dataInfo is the json you posted, then you have to access information and from information, you can access data:
JSONObject data = new JSONObject(dataInfo);
JSONObject info = data.optJSONObject("information");
if (info != null) {
JSONArray dataArray = info.optJSONArray("data")
}