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
Related
I have a JSON Arrays of Array like this
"results": [
{
"id": "AAA",
"color": "#4D4837",
"links": {
"self": "https://aaa.com",
"html": "https://bbb.com",
"download": "https://ccc.com",
"download_location": "ddd.com"
},
"categories": [],
"likes": 3891,
},
{
"id": "BBB",
"color": "#4D453",
"links": {
"self": "https://abb.com",
"html": "https://bcc.com",
"download": "https://ccc.com",
"download_location": "ddd.com"
},
"categories": [],
"likes": 3000,
}
]
And I would like to retrieve "https://bbb.com" and "https://bcc.com" of "html", but I don't know how to do that.
Based on kindly comment, I put the following.
somehow, "getJSONObject()"can not be put. The error message says "Cannot resolve method 'getJSONObject' in 'JSONArray'".
JSONArray array = new JSONArray((Collection) jobjt.get("Strings"));
for (int i =0 ; i<2 ; i++){
JSONObject job = (JSONObject) array.get(i); --> get(i) can not be changed to getJSONObject(i)
String id = job.get("id").toString();
String color = job.get("color").toString();
String photoUrl = job.get("links").toString(); --> By updating here, I want to store only "https://bbb.com" and "https://bcc.com".
}
But when I tried to use the following, not only "html", but "self" and the other information are retrieved.
String photoUrl = job.get("links").toString();
Please tell me how to retrieve only "html".
I am using IntelliJ.
Steps to be followed(assuming you have proper JSONArray you mentioned):
get JSONObject from your JSONArray by index ie. for your case, index=0 here
Get the inner JSONObject by key of links
Now, access your content by key of html
Example for your case:
JSONObject indexedObject = jsonArray.getJSONObject(0);
JSONObject linksObject = indexedObject.getJSONObject("links");
String html= linksObject.getString("html");
Better keep checking if key exists as Harshal suggests
How to structure Multiple array of JSON in the beanshell sampler
for example i need to pass N number of articles to a loop , so i have created a for loop to fetch the articles. here i have mentioned 3 articles as an example. but i need to fetch N number of articles in a loop.
The output should be like :
"itemLines": {
"itemLine": [
{
"bundleParentId": "",
"id": "1",
"itemType": "ART",
"itemNo": "1234",
},
{
"bundleParentId": "",
"id": "2",
"itemType": "ART",
"itemNo": "2021",
},{
"bundleParentId": "",
"id": "3",
"itemType": "ART",
"itemNo": "2023",
}
]
}
My code in the beanshell smpler is : For example here i have mentioned in the array list with 3 article numbers.
public void createJsonStructure() {
try
{
JSONObject rootObject = new JSONObject();
JSONArray articleArr = new JSONArray();
String[] article_list = {"00258882", "70234185", "00258882"};
log.info(article_list.length);
for (i=0;i<=article_list.length;i++)
{
JSONObject article_list= new JSONObject();
article_list.put("id", "i+1");
article_list.put("itemNo",article_list[i]);
article_list.put("requiredQty", "1");
articleArr.put(article_list);
}
log.info(articleArr);
rootObject.put("itemLines", articleArr);
log.info("rootObject is"+rootObject.toString(4));
props.put("JsonObjectoutput", rootObject.toString(4));
}
catch (Exception ex)
{
ex.printStackTrace();
log.info("notes");
}
}
I could see the output is not retrieved in the jmeter logs . Here output should be printed in the logs , but i could see output is not printed.
I have a json arrary with many json messsages. I then parse the json message to process each json object.
I need to figure out how to take a single json object that fails and append all the failed json objects back
into another json array to create a new file. I'm not sure how to convert a json object from the parseText() method
back to a normal json message or how to append objects back into a json array to create a file. Can someone help me with this?
Main json file array
[
{
"Account": "1",
"Name": "Test1"
},
{
"Account": "2",
"Name": "Test2"
},
{
"Account": "3",
"Name": "Test3"
},
{
"Account": "4",
"Name": "Test4"
}
]
String sJson = groovy.json.StringEscapeUtils.unescapeJava(jsonFile.toString());
jsonResp = new groovy.json.JsonSlurper().parseText(sJson));
for( int x=0; x < jsonResp?.size(); x++ ) {
processJson( jsonResp[x] )
}
void processJson( Object jsonResp ) {
If object message fails in this function, need to convert the json object back into a json message
and append it to a jsonArray to create a new json file.
}
This is what the new json file would like if test samples 2 & 4 failed
[
{
"Account": "2",
"Name": "Test2"
},
{
"Account": "4",
"Name": "Test4"
}
]
I found the answer to my question.
JSONArray jsonArray = new JSONArray();
jsonArray.add(jsonResp);
println jsonArray.toString()
I am working with Android Studio, andI have a string variable, called sResponse (below). According to the debugger, it holds the following value:
{
"responseData": {
"emotion":"",
"lastinput":{actionResult={"value":{"label":"green","key":"1"},"result":"success","action":"displayClickableList"},
"answer":"Sorry, I did not understand.",
"link": {
"href":"",
"target":""
},
"extraData": {
},
"responseSession": {
"id":"c4a5ef257851a991eb32c69132c9",
"transaction":"4"
},
"responseDetails": "null",
"responseStatus": "200",
"applicationUrl": "http://noki-dev.cloud.com:90/moto-1/"
}
}
When I try to initialize a JSONObject with it with in this way:
jResponse=new JSONObject(sResponse);
...The following exception rises in my Logcat:
>>>>>>>>>Thread EXCEPTION1: Response with invalid JSON format: , FrontendActivity.java L:421 ***** *org.json.JSONException: Unterminated object at character 502 of : sResponse
I suspect that those // in the URL are causing trouble. I am no expert in escaping JSON Characters. How can I obtain a valid JSONObject from the previous string? What trouble can you spot in my approach?
Problem caused because of = sign near by actionResult as well as actionResult not surrounded with double quotes and you didn't close json string properly.
Replace Json String With:
{
"responseData": {
"emotion":"",
"lastinput":{"actionResult":{"value":{"label":"green","key":"1"},"result":"success","action":"displayClickableList"},
"answer":"Sorry, I did not understand.",
"link": {
"href":"",
"target":""
},
"extraData": {
},
"responseSession": {
"id":"c4a5ef257851a991eb32c69132c9",
"transaction":"4"
},
"responseDetails": "null",
"responseStatus": "200",
"applicationUrl": "http://noki-dev.cloud.com:90/role-va-1/"
}
}
}
and add } at the end of the string.
You can track the error using following online tool:
http://json.parser.online.fr/
You missed last closing curly at the end of the response.
Just add } on last line.
Corrected json Response
{
"responseData": {
"emotion": "",
"lastinput": {
actionResult: {
"value": {
"label": "green",
"key": "1"
},
"result": "success",
"action": "displayClickableList"
},
"answer": "Sorry, I did not understand.",
"link": {
"href": "",
"target": ""
},
"extraData": {
},
"responseSession": {
"id": "c4a5ef257851a991eb32c69132c9",
"transaction": "4"
},
"responseDetails": "null",
"responseStatus": "200",
"applicationUrl": "http://noki-dev.cloud.com:90/moto-1/"
}
}
}
At the moment i'm trying to understand json and how it works.
But i have a problem with an array of objects.
all objects in the array have a key called "value" (i know it's weird, it's not my code) what also is an object.
And now to the problem: This object called "value" has always different key-values.
So i dont now how i can parse the json code to java object code, when it differ, every time.
Here some examples:
First object of the array:
"value":
{
"local":
[
"English", "Deutsch", Espanol"
],
"english":
[
"English", "Deutsch", Espanol"
],
},
Second object(now a string, not object) of the array:
"value" : "",
Third object of the array:
"value" : {},
...
Maybe I'm doing the parsing wrong.
First I have created the beans classes in java for the json code and then I'm using the automatic parser of google. (gson)
It works when only one of the examples above is inside the json code. (it should not differ, like changing from string to object...)
Gson gson = new Gson();
Output output = gson.fromJson(json, Output.class);
Output is the main class for the json stuff.
I have found out that maybe while parsing I could check a value called "id" first, and from that I could create another beans class with the right variables ...
Thats the code i need to parse to java objects and how do you do that??
The problem is the key called "value", because its always different.
With my method of using the google parser "gson" it wont work, because i'm getting exception that its an string but i was waiting for an object...
{
"status":"success",
"data":{
"panel":{
"title":{
"label":{ "local":"Tote Selection", "english":"Tote Selection" },
"image":"public/img/pick.jpg", "type":"default"
},
"isFirst":false, // currently not used
"isLast":false, // currently not used
"ownCount":0, // currently not used
"panelsCount":0, // currently not used
"elements":[
{
"type":"text",
"id":"1", "value":{ "local":"Scan next order tote",
"english":"Scan next order tote" },
"label":{ "local":"", "english":"" }, "color":"000000",
"fontsize":18, "fontstyle":"flat", "alignment":"left",
"rows":"undefined", "bgcolor":"", "isFocus":false
},
{
"type":"text",
"id":"4", "value":{ "local":"Scan tote: ", "english":"Scan tote: " },
"label":{ "local":"", "english":"" }, "color":"000000", "fontsize":20,
"fontstyle":"strong", "alignment":"left", "rows":"undefined",
"bgcolor":"", "isFocus":false
},
{
"type":"input",
"id":"6", "value":"", "label":{ "local":"", "english":"" },
"color":"000000", "fontsize":24, "fontstyle":"flat", "alignment":"left",
"rows":"undefined", "isFocus":true
},
{
"type":"button",
"id":"1", "value":{ "local":"", "english":"" },
"label":{ "local":"Menu", "english":"Menu" }, "color":"000000",
"fontsize":14, "fontstyle":"strong", "alignment":"left",
"rows":"undefined", "isFocus":false
},
{
"type":"button",
"id":"4", "value":{ "local":"", "english":"" },
"label":{ "local":"Enter", "english":"Enter" }, "color":"000000",
"fontsize":14, "fontstyle":"strong", "alignment":"right",18
"rows":"undefined", "isFocus":false
}
]
},
"authToken":"0fdd440a-619f-4936-ab74-d189accb5bd9",
"routing":{
"controller":"panel",
"action":"process",
"workflowId":"singlepicking",
"taskId":"orderSelection"
}
}
}
Thank you for your help!
it looks a little bit different but your answer helped me! Thx
JsonParser parser = new JsonParser();
JsonObject obj = parser.parse(br).getAsJsonObject();
//now getting all the json values
String status = obj.get("status").getAsString();
JsonObject data = obj.getAsJsonObject("data");
String authToken = data.get("authToken").getAsString();
JsonObject routing = data.getAsJsonObject("routing");
String controller = routing.get("controller").getAsString();
String action = routing.get("action").getAsString();
String workflowId = routing.get("taskId").getAsString();
If I understood ur question properly u can retrieve the values of the JSONArray as below
for (int i = 0; i < JArray.length(); i++) {
print(JArray.getJSONObject(i).tostring())
}
So if i am right u are getting the JSON from a String First?? so please try below first store the String in JSONObject as JSONObject obj = new JSONObject(str);//str is the string that u are getting
to get the valueenglish that are in data-panel-tittle-label is
String englishinLable=obj .getJSONObject("data").getJSONObject("panel").getJSONObject("title").getJSONObject("label").optString("english")