Incorrect JSON format sent from an app - java

How can I send JSONArray from Android client to server?
getJsonArray() is a function which return an JsonArray but when I send array to server it looks like this:
{
"IMEI": "xxxxxxxxxxxxxxx",
"Puls": ["101", "125", "103", "81"],
"Pasi": ["0", "0", "0", "0"],
"Latitudine": ["0", "0", "0", "0"],
"Longitudine": ["0IMEI=xxxxxxxxxxxxxxx", "0IMEI=xxxxxxxxxxxxxxx", "0IMEI=xxxxxxxxxxxxxxx", "0"]
}
I don't know why first IMEI is on right place and the others is not...
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
for (int i = 0; i < getJsonArray().length(); i++) {
writer.write(getPostDataString(getJsonArray().getJSONObject(i)));
}

The array inside the main array should look like this for example :-
"Puls": [
{
"number" : "101"
},
{
"number" : "125"
},
{
"number" : "103"
},
{
"number" : "81"
},
]
Try to format the arrays like this...

String strloadMainCategory = "api"+URLEncoder.encode("","UTF-8");
RestClient restClient = new RestClient(strloadMainCategory);
try {enter code here
restClient.Execute(RequestMethod.GET);
} catch (Exception e) {}

Related

How to structure Multiple array of JSON in the beanshell sampler

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.

Second JSONArray in JSONObject somehow is empty

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

Delete a child attribute from json file

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));
}

Accessing json string in java and creating hashmap Android

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")
}

android get duration from maps.google.com directions

At the moment I am using this code to inquire google maps for directions from an address to another one, then I simply draw it on a mapview from its GeometryCollection. But yet this isn't enough I need also to extract the total expected duration from the kml. can someone give a little sample code to help me? thanks
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.google.com/maps?f=d&hl=en");
urlString.append("&saddr=");//from
urlString.append( Double.toString((double)src.getLatitudeE6()/1.0E6 ));
urlString.append(",");
urlString.append( Double.toString((double)src.getLongitudeE6()/1.0E6 ));
urlString.append("&daddr=");//to
urlString.append( Double.toString((double)dest.getLatitudeE6()/1.0E6 ));
urlString.append(",");
urlString.append( Double.toString((double)dest.getLongitudeE6()/1.0E6 ));
urlString.append("&ie=UTF8&0&om=0&output=kml");
//Log.d("xxx","URL="+urlString.toString());
// get the kml (XML) doc. And parse it to get the coordinates(direction route).
Document doc = null;
HttpURLConnection urlConnection= null;
URL url = null;
try
{
url = new URL(urlString.toString());
urlConnection=(HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
dbf = DocumentBuilderFactory.newInstance();
db = dbf.newDocumentBuilder();
doc = db.parse(urlConnection.getInputStream());
if(doc.getElementsByTagName("GeometryCollection").getLength()>0)
{
//String path = doc.getElementsByTagName("GeometryCollection").item(0).getFirstChild().getFirstChild().getNodeName();
String path = doc.getElementsByTagName("GeometryCollection").item(0).getFirstChild().getFirstChild().getFirstChild().getNodeValue() ;
//Log.d("xxx","path="+ path);
String[] pairs = path.split(" ");
String[] lngLat = pairs[0].split(","); // lngLat[0]=longitude lngLat[1]=latitude lngLat[2]=height
// src
GeoPoint startGP = new GeoPoint((int)(Double.parseDouble(lngLat[1])*1E6),(int)(Double.parseDouble(lngLat[0])*1E6));
mMapView01.getOverlays().add(new MyOverLay(startGP,startGP,1));
GeoPoint gp1;
GeoPoint gp2 = startGP;
for(int i=1;i<pairs.length;i++) // the last one would be crash
{
lngLat = pairs[i].split(",");
gp1 = gp2;
// watch out! For GeoPoint, first:latitude, second:longitude
gp2 = new GeoPoint((int)(Double.parseDouble(lngLat[1])*1E6),(int)(Double.parseDouble(lngLat[0])*1E6));
mMapView01.getOverlays().add(new MyOverLay(gp1,gp2,2,color));
//Log.d("xxx","pair:" + pairs[i]);
}
mMapView01.getOverlays().add(new MyOverLay(dest,dest, 3)); // use the default color
}
}catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}catch (SAXException e){
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
}
Use the new Directions api. The duration is returned in the response and no more parsing of KML, which I think breaks the Google maps license terms anyways.
Update. Ok use the JSON output, with it parsing is built into Android.
Ex url
Response is
{
"status": "OK",
"routes": [ {
"summary": "I-40 W",
"legs": [ {
"steps": [ {
"travel_mode": "DRIVING",
"start_location": {
"lat": 41.8507300,
"lng": -87.6512600
},
"end_location": {
"lat": 41.8525800,
"lng": -87.6514100
},
"polyline": {
"points": "a~l~Fjk~uOwHJy#P",
"levels": "B?B"
},
"duration": {
"value": 19,
"text": "1 min"
},
"html_instructions": "Head \u003cb\u003enorth\u003c/b\u003e on \u003cb\u003eS Morgan St\u003c/b\u003e toward \u003cb\u003eW Cermak Rd\u003c/b\u003e",
"distance": {
"value": 207,
"text": "0.1 mi"
}
},
...
... additional steps of this leg
...
... additional legs of this route
"duration": {
"value": 74384,
"text": "20 hours 40 mins"
},
"distance": {
"value": 2137146,
"text": "1,328 mi"
},
"start_location": {
"lat": 35.4675602,
"lng": -97.5164276
},
"end_location": {
"lat": 34.0522342,
"lng": -118.2436849
},
"start_address": "Oklahoma City, OK, USA",
"end_address": "Los Angeles, CA, USA"
} ],
"copyrights": "Map data ©2010 Google, Sanborn",
"overview_polyline": {
"points": "a~l~Fjk~uOnzh#vlbBtc~#tsE`vnApw{A`dw#~w\\|tNtqf#l{Yd_Fblh#rxo#b}#xxSfytAblk#xxaBeJxlcBb~t#zbh#jc|Bx}C`rv#rw|#rlhA~dVzeo#vrSnc}Axf]fjz#xfFbw~#dz{A~d{A|zOxbrBbdUvpo#`cFp~xBc`Hk#nurDznmFfwMbwz#bbl#lq~#loPpxq#bw_#v|{CbtY~jGqeMb{iF|n\\~mbDzeVh_Wr|Efc\\x`Ij{kE}mAb~uF{cNd}xBjp]fulBiwJpgg#|kHntyArpb#bijCk_Kv~eGyqTj_|#`uV`k|DcsNdwxAott#r}q#_gc#nu`CnvHx`k#dse#j|p#zpiAp|gEicy#`omFvaErfo#igQxnlApqGze~AsyRzrjAb__#ftyB}pIlo_BflmA~yQftNboWzoAlzp#mz`#|}_#fda#jakEitAn{fB_a]lexClshBtmqAdmY_hLxiZd~XtaBndgC",
"levels": "BBBAAAAABAABAAAAAABBAAABBAAAABBAAABABAAABABBAABAABAAAABABABABBABAABB"
},
"warnings": [ ],
"waypoint_order": [ 0, 1 ]
} ]
}
Let's say you used the standard http client libraries and now have the response in a String.
JSONObject jsonObject = new JSONObject(response); // parse response into json object
JSONObject routeObject = jsonObject.getJSONObject("route"); // pull out the "route" object
JSONObject durationObject = jsonObject.getJSONObject("duration"); // pull out the "duration" object
String duration = durationObject.getString("text"); //this should be the duration text value (20 hours 40 mins)
You will have to wrap all that in a try-catch block to catch the JSONExceptions.

Categories

Resources