I need my app to send an ArrayList<String[]> to php, I have this to call the service:
ArrayList<String[]> Items = new ArrayList<String[]>();
(...)
JSONObject JSONSend= new JSONObject();
JSONSend.put("Items", Items );
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;
HttpPost post = new HttpPost(SERVICE);
post.setHeader("json", JSONSend.toString());
StringEntity se = new StringEntity(JSONSend.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
post.setEntity(se);
response = client.execute(post);
and on the PHP service:
$data = file_get_contents('php://input');
$json = json_decode($data);
$Items = $json->{'Items'};
error_log($Items);
and the php is returning this:
[[Ljava.lang.String;#413e2fd0, [Ljava.lang.String;#413a2940, [Ljava.lang.String;#4139df18, [Ljava.lang.String;#4141b5b0, [Ljava.lang.String;#413931c8, [Ljava.lang.String;#41348b40, [Ljava.lang.String;#41393928]
The type of the $ServMade is string, so how can I take care of the data as an array on php? Am I missing something?
Try the following when generating json string in android:
JSONObject JSONSend= new JSONObject();
JSONArray ja = null;
JSONArray tmp = new JSONArray();
for(String s[] : Items){
ja = new JSONArray();
for(int i = 0; i<s.length; i++)
ja.put(s[i]);
tmp.put(ja);
}
JSONSend.put("Items", tmp);
The problem here is that You call .toString() (within Java) on an array of strings (String[]) that while NOT overrided returns exactly what You get in the JSON: [Ljava.lang.String;#413e2fd0].
Don't know exactly the JSONObject but I guess You should transform the ArrayList<String[]> (so the array of arrays of strings) to something different for JSONObject to handle it correctly.
Also, in PHP, You do not have to call $Items = $json->{'Items'}; - it is okay to call $Items = $json->Items;.
Related
I have a StringBuilder:
My code is the following:
String response = sb.toString();
// logger.info("response is '{}' ", response);
JsonObject jsonObject = new JsonObject(response);
JsonObject fileStatuses = jsonObject.getJsonObject("FileStatuses");
JsonArray fileStatus = (JsonArray) fileStatuses.getJsonArray("FileStatus");
for (int i = 0; i < fileStatus.size(); ++i) {
JsonObject rec = fileStatus.getJsonObject(i);
String pathSuffix = rec.getString("pathSuffix");
logger.info(" the pathSuffix value is '{}' ", pathSuffix );
}
I want to use the javax.json.JsonObject and not org.json.JsonObject.
So, the problem is in new JsonObject(response); ==> Cannot instantiate the type JsonObject.
I know that org.json.JSONObject has a constructor that takes a String, but I think not the case when using javax.json.JsonObject.
How can I correct my code to make JsonObject jsonObject = new JsonObject(response) take a String and stay using javax.json.JsonObject class?
According to its API instead of using JsonObject jsonObject = new JsonObject(response); you can instantiate it from your response-String like this:
String response = sb.toString();
StringReader reader = new StringReader(response);
JsonReader jsonReader = Json.createReader(reader);
JsonObject jsonObject = jsonReader.readObject();
jsonReader.close();
Actually, I have a JSONObject like this:
JSONObject json = new JSONObject();
json.put("type", "login");
json.put("friendList", FriendList);
and the FriendListis the type of ArrayList<String[]>
, then I use a socket to transfer JSON to my client.
My client received the data:
JSONObject receive_msg = new JSONObject(data);
String type = receive_msg.getString("type");
My question is how to get friendList with data typeArrayList<String[]>?
Thanks a lot if anyone helps.
you need to use JsonArray, iteratore over your list and fill the jsonArray then put it in the JsonObject
http://docs.oracle.com/javaee/7/api/javax/json/JsonArray.html
I am sending API call to a service that return a json array like this :
[Object, Object ....]
via my java http request. the resulat are stored in a string:
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
I need to find a way to split this string to by json objects so each new string will contain only one object.
Thanks.
Instead of using the split function, you can convert your String to a JSONArray and then iterate throw the array
JSONArray jsonArray = new JSONArray(response.toString());
for(int i=0; i<jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String jsonObjectAsString = jsonObject.toString();
}
I have string in JSON format. For example:
{
"blockedStatus":true,
"cars":[
"RAW:123",
"TVU:123"
],
"phones":[
"370665566",
"3706324231"
]
}
This is output from server. I need to get seperate values but I don't know how to do it.
Tried this:
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
JSONTokener tokener = new JSONTokener(builder.toString());
JSONArray finalResult = new JSONArray(tokener);
Log.e("IO-OUTPUT", builder.toString()); //prints json output
Log.e("finalResult (1)", finalResult.getString(1));
But I get ant exception:
W/System.err(31249): org.json.JSONException: Value {"blockedStatus":true,"cars":["RAW"],"phones":["65431"]} of type org.json.JSONObject cannot be converted to JSONArray
Is there another way to get values? Because calculating symbols and getting values from it will be too hard
change
JSONTokener tokener = new JSONTokener(builder.toString());
JSONArray finalResult = new JSONArray(tokener);
to
JSONObject jsonObject = new JSONObject(builder.toString());
JSONArray carsResult = jsonObject.getJSONArray("cars");
JSONArray phoneResult = jsonObject.getJSONArray("phones");
your string rapresent a JSONObject which contains two JSONArray's, cars and phones, and a pair key/value blockedStatus .
Also, if you read the logcat, it says:
type org.json.JSONObject cannot be converted to JSONArray
You can not convert a JSONObject to a JSONArray, which means the you have a JSONObject
Try this
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
InputStream ips = response.getEntity().getContent();
responseString = response.toString();
responseString = intputStreamToStringConvertor(ips);
JSONObject object = new JSONObject(responseString);
Boolean status = object.getBoolean("blockedStatus");
JsonArray cars = object.getJSONArray("cars");
JsonArray phones = object.getJSONArray("phones");
I have this following method that connectss to db and returns a json array.
private String getServerData(String returnString) {
InputStream is = null;
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year","1970"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(KEY_121);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
// JSONObject json_data = jArray.getJSONObject(i);
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getInt("id")+
", name: "+json_data.getString("name")+
", sex: "+json_data.getInt("sex")+
", birthyear: "+json_data.getInt("birthyear")
);
//Get an output to the screen
returnString += "\n\t" + jArray.getJSONObject(i);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
returnString += result.toString();
}
return returnString;
}
I then want to call this method from outside but being very new to java I am not sure how to get that sting in put it in hm object like the one thats commented out. See the code below
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView listView = (ListView)findViewById(R.id.list);
myBooks = new ArrayList<HashMap<String,Object>>();
HashMap<String, Object> hm;
hm = new HashMap<String, Object>();
List<String> list=new ArrayList<String>();
list.add(getServerData(KEY_121));
//With the help of HashMap add Key, Values of Book, like name,price and icon path
/* hm = new HashMap<String, Object>();
hm.put(BOOKKEY, "Android");
hm.put(PRICEKEY, "Price Rs: 500");
hm.put(IMGKEY, R.raw.android); //i have images in res/raw folder
myBooks.add(hm);
SimpleAdapter adapter = new SimpleAdapter(this, myBooks, R.layout.listbox,
new String[]{BOOKKEY,PRICEKEY,IMGKEY}, new int[]{R.id.text1, R.id.text2, R.id.img});
listView.setAdapter(adapter);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
My object here is to get the returning string and add it to the myBooks object by using hm object just like how its done in the commented code.
Thanks
Since getServerData() is going to take a while to execute (it contains an http request), you cannot run it directly from the UI thread. (onCreate() is directly on the UI thread, and the UI thread should never be paused).
This means you have to create an AsyncTask and call getServerData() from the doInBackground() of your AsyncTask. You can return the display JSON result in the AsyncTask's onPostExecute().
This means that you want to pass a SoftReference of where you want to show your result to the AsyncTask. You want to make it a SoftReference in case something happens while you're fetching the JSON (like you navigate away from the Activity).
I would suggest that you read this Android blog article and create your own project with the code from the article. Once you have that up and running, modify the that image downloader to a JSON downloader. The article should be really helpful to you, since it also uses an Adapter to show items in a List View.
Your example is different from the one in the article in several ways, but I think it's actually simpler, so if you get your head wrapped around the code in the article, then you'll be able to get your code working afterward.
References:
AsyncTask
SoftReferences
Multithreading for Performance
Working Code from the Article Above which implements something like you want but w images
here is what I did and it works just fine
1- instead of returning the string, i returned the result as it is to the call.
2 then after that I built a string and then I was able to parse it just fine like this
returnedResult = this.getServerData(KEY_121);
try {
JSONArray jArray = new JSONArray(returnedResult);
for(int i=0;i<jArray.length();i++){
// JSONObject json_data = jArray.getJSONObject(i);
JSONObject json_data = jArray.getJSONObject(i);
hm = new HashMap<String, Object>();
hm.put(IDKEY, json_data.getInt("id"));
hm.put(NAMEKEY, json_data.getString("name"));
hm.put(IMGKEY, R.raw.android);
myBooks.add(hm);
}
Hope that helps to someone here
thanks