I produce a json like this:
["\"latitud\":\"123.0\",\"orden\":\"0\",\"longitud\":\"123.0\",\"urlfoto\":\"a\",\"idruta\":\"45\"}","{\"latitud\":\"321.0\",\"orden\":\"1\",\"longitud\":\"321.0\",\"urlfoto\":\"b\",\"idruta\":\"45\"}","{\"latitud\":\"231.0\",\"orden\":\"2\",\"longitud\":\"231.0\",\"urlfoto\":\"c\",\"idruta\":\"45\"}"]
I search here and I have tryed:
$puntos = $_POST['puntos'];
$data = json_decode($puntos,true);
foreach($data as $obj) {
$idruta = $obj['idruta'];
$orden = $obj['orden'];
$urlfoto = $obj['urlfoto'];
$longitud = $obj['longitud'];
$latitud = $obj['latitud'];
}
Illegal string offset 'idruta'
foreach($data as $obj) {
$idruta = $obj->idruta;
$orden = $obj->orden;
$urlfoto = $obj->urlfoto;
$longitud = $obj->longitud;
$latitud = $obj->latitud;
}
Trying to get property of non-object
foreach($data as $obj) {
$idruta = $obj[0];
$orden = $obj[1];
$urlfoto = $obj[2];
$longitud = $obj[3];
$latitud = $obj[4];
}
obj[i] is always 0 and no errors.
The loop do 3 times so that's ok.
Sorry I'm just learning JSON and php, I will very glad if anybody can help me getting the data of the JSON.
Thanks!
EDIT: Thanks for the answers!
I don't know why is missing the "{" and when i paste the same json in JSONlint for example its validates fine so... I'm a little lost sorry.
That's the way I am sending the json:
public void insertPoints(ArrayList<Punto> puntos){
JSONArray array = new JSONArray();
List<NameValuePair> params = new ArrayList<NameValuePair>();
for(Punto p:puntos){
JSONObject obj = new JSONObject();
try {
obj.put("idruta",Integer.toString(p.getIdruta()));
obj.put("orden",Integer.toString(p.getOrden()));
obj.put("urlfoto",p.getUrlfoto());
obj.put("longitud",Double.toString(p.getLongitud()));
obj.put("latitud",Double.toString(p.getLongitud()));
array.put(obj.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpClient httpClient = new DefaultHttpClient();
try {
HttpPost request = new HttpPost(CREATE_POINT);
StringEntity params =new StringEntity("puntos=" + postjson);
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
// handle response here...
} catch (Exception ex) {
// handle exception here
} finally {
httpClient.getConnectionManager().shutdown();
}
}
is here any problem?
Thanks!
Your JSON represents an array of strings. All { and } are inside "..." and are interpreted as part of a string. So, you can't access 'idruta' and other fields without further parsing because they all are inside a single string. You should change JSON code if you can.
You problem is caused by array.put(obj.toString());. You shouldn't do it. Also I think you should remove Integer.toString from obj.put("idruta",Integer.toString(p.getIdruta())); and similar lines. See this question.
First of all, { is missing in first line of JSON.
Try this:
$data = json_decode($puntos,true);
instead of:
$data = json_decode($puntos);
It should work!
Related
I have an arraylist containing multiple rows of data I wish to pass from android to a PHP server where it is displayed. I placed the arraylist contents in a JSON object which I pass on to a name-value-pair list before parsing.
My problem is when i output the value of the recieved JSON. It only displays the last of records.
PHP CODE:
<?php
if($_POST)
{
echo "Smething was sent";
$JSON_Entry = $_POST["Entry"];
$obj = json_decode($JSON_Entry);
$i = 0;
print_r($obj);
}
?>
JAVA CODE:
ArrayList<SalesReciepts> entryList = db.getSalesRecords();
List<NameValuePair> postVars = new ArrayList<NameValuePair>();
for (int i = 0; i < entryList.size(); i++) {
try {
JSONentry.put("id", String.valueOf(entryList.get(i).getEntryId()));
JSONentry.put("invoice",String.valueOf(entryList.get(i).getInvoice_id()));
JSONentry.put("product", String.valueOf(entryList.get(i).getProduct()));
JSONentry.put("qty", String.valueOf(entryList.get(i).getQty()));
JSONentry.put("total", String.valueOf(entryList.get(i).getTotal()));
}
catch(JSONException e) {
e.printStackTrace();
}
}
JSONObject sent = new JSONObject();
try {
sent.put("records", String.valueOf(JSONentry));
}
catch(JSONException e) {
e.printStackTrace();
}
postVars.add(new BasicNameValuePair("Entry", String.valueOf(sent)));
//Declare and Initialize Http Clients and Http Posts
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(POST_PRODUCTS);
//Format it to be sent
try {
httppost.setEntity(new UrlEncodedFormEntity(postVars));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
/* Send request and Get the Response Back */
try {
HttpResponse response = httpclient.execute(httppost);
String responseBody = EntityUtils.toString(response.getEntity());
Log.e("response:", responseBody );
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.v("MAD", "Error sending... ");
} catch (IOException e) {
e.printStackTrace();
Log.v("MAD", "Error sending... ");
}
OUTPUT:
Smething was sent{"records":"{\"total\":\"1398.0\",\"product\":\"Carlsberg\",\"id\":\"0\",\"qty\":\"2\",\"invoice\":\"2.4082015083321E13\"}"}
The output displays the last of 3 rows/records
You need to create a new JSONentry for each loop iteration, then add it to your JSONArray.
Change your code like that:
ArrayList<SalesReciepts> entryList = db.getSalesRecords();
List<NameValuePair> postVars = new ArrayList<NameValuePair>();
JSONArray recordsJsonArray = = new JSONArray();
for (int i = 0; i < entryList.size(); i++) {
try {
JSONObject JSONentry = new JSONObject(); // here you create a new JSONObject
JSONentry.put("id", String.valueOf(entryList.get(i).getEntryId()));
JSONentry.put("invoice",String.valueOf(entryList.get(i).getInvoice_id()));
JSONentry.put("product", String.valueOf(entryList.get(i).getProduct()));
JSONentry.put("qty", String.valueOf(entryList.get(i).getQty()));
JSONentry.put("total", String.valueOf(entryList.get(i).getTotal()));
recordsJsonArray.put(JSONentry); // here you add the item to your array
}
catch(JSONException e) {
e.printStackTrace();
}
}
JSONObject sent = new JSONObject();
try {
sent.put("records", String.valueOf(recordsJsonArray));
}
catch(JSONException e) {
e.printStackTrace();
}
postVars.add(new BasicNameValuePair("Entry", String.valueOf(sent)));
You have to create a new JSONentry after every loop. Right now you only are overriding the last set value over and over again.
Without being a Java specialist, but I would say you need to
change this line and the following ones
JSONentry.put("id", String.valueOf(entryList.get(i).getEntryId()));
with something like "id[]"
but again - I am not a JAVA expert, but it strongly looks like you are overriding the same values over and over and therefore only the last is caught in PHP script.
Your JSONEntry is a JSONObject. You need to make a JSONArray where you will put your different JSONEntry
I searched for a lot of topics here on SO and I came pretty far. But now I have a problem, concerning how to correctly read data from this URL:
http://gdata.youtube.com/feeds/api/playlists/PLsksxTH4pR3KtrWWeupRy5h0Di7N_MufB?v=2&alt=jsonc&max-results=50
In position 22 there is a video that is rejected from Youtube and therefore blocked, so one cannot watch it. I now have the problem that I cannot successfully skip that entry and continue with the next one. Even though there are 50 entries in the above URL, my application will only display 21, stopping where that blocked video would be.
I tried to use the JsonObject "status" of that video and checking if it has the value "rejected", but I couldn't do it.
Any help is welcome, thanks in advance :)
Here is my code:
ArrayList<String> msg = new ArrayList<String>();
ArrayList<String> title = new ArrayList<String>();
ArrayList<Bitmap> thumb = new ArrayList<Bitmap>();
public void getData()
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet("http://gdata.youtube.com/feeds/api/playlists/PLsksxTH4pR3KtrWWeupRy5h0Di7N_MufB?v=2&alt=jsonc&max-results=50");
try
{
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
String _response= EntityUtils.toString(resEntity); // content will be consume only once
JSONObject json = new JSONObject(_response);
JSONArray jsonArray = json.getJSONObject("data").getJSONArray("items");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i).getJSONObject("video");
String title1 = jsonObject.getString("title");
title.add(title1);
String thumbUrl = jsonObject.getJSONObject("thumbnail").getString("sqDefault");
URL url1 = new URL(thumbUrl);
Bitmap bmp = BitmapFactory.decodeStream(url1.openConnection().getInputStream());
thumb.add(bmp);
String url;
try {
url = jsonObject.getJSONObject("player").getString("default");
msg.add(url);
} catch (JSONException ignore) {
}
}
}
catch(Exception e1)
{
e1.printStackTrace();
}
httpclient.getConnectionManager().shutdown();
}
I tried to use the JsonObject "status" of that video and checking if
it has the value "rejected", but I couldn't do it.
To get all items from items JSONArray without blocked items. use JSONObject.has method for checking is status object is available or not before accessing other keys from video JSONObject.like:
JSONObject jsonObject = jsonArray.getJSONObject(i).getJSONObject("video");
if(jsonObject.has("status")){
// ignore video object
}else{
//... get other thumbnail, player objects
}
I know how to asynchronously do a Request.newMyFriendsRequest(session,Request.GraphUserListCallback) and in the callback method you have access to the List<GraphUser> element. The question is how do you do this in a background thread.
What I have so far is
Request friendsRequest = new Request(session,"/me/friends");
Response response = friendsRequest.executeAndWait();
GraphObject obj = response.getGraphObject();
How do I convert obj to a List<GraphUser> or is there a better way and I'm just missing something?
I figured out a way to do it to get me through right now. but I don't know if this is the best way.
So what I did was just grab the whole JSON response from facebook and parse out what I wanted.
try {
Request friendsRequest = new Request(session, "/me/friends");
Response response = friendsRequest.executeAndWait();
JSONObject responseJSON = new JSONObject(response.getRawResponse());
JSONArray data = responseJSON.getJSONArray("data");
if (data.length() > 0) {
for (int i = 0; i < data.length(); i++) {
JSONObject friend = (JSONObject) data.get(i);
String name = friend.getString("name");
String facebookID = friend.getString("id");
// Do Stuff With name and facebookID
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (FacebookException e) {
e.printStackTrace();
}
Make sure to catch the FacebookException otherwise you'll get force closes when the user has no data connection
I was trying to get an JSONObject from a HTTP response.
try
{
GetMethod postMethod = new GetMethod();
postMethod.setURI(new URI(url, true));
postMethod.setRequestHeader("Accept", "application/json");
httpClient.executeMethod(postMethod);
String resp=postMethod.getResponseBodyAsString();
org.json.JSONTokener tokener = new org.json.JSONTokener(resp);
finalResult = new org.json.JSONArray(tokener);
return finalResult;
}
But I got a runtime warning as
Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.
Should I get the response as stream as suggested by the JVM ? If so, how could I parse the JSON from it ?
Has your server been set up to inform clients how big its responses are? If not, your server is streaming the data, and it's technically impossible to tell how much buffer space is required to deal with the response, warranting a warning that something potentially dangerous is going on.
if you want to send jsonObjects from server suppose (tomcat server)
For server side-
creating jsonobjects-
I have Called toJson() for creating jsonobjects this is the implementation-
final JSONObject arr = new JSONObject();
for (int i = 0; i < contactStatus.size(); i++) {
ContactStatus contactObject = contactStatus.get(i);
try {
arr.put(String.valueOf(i), toJson(value1, value2,, value3));
} catch (JSONException e) {
catch block e.printStackTrace();
}
}
//Here we serialize the stream to a String.
final String output = arr.toString();
response.setContentLength(output.length());
out.print(output);//out is object of servlet output stream.
public static Object toJsonForContact(String value1, boolean value2, double value3) throws JSONException {
JSONObject contactObject = new JSONObject();
contactObject.put("id", id);
contactObject.put("status", value1);
contactObject.put("distance", value2);
contactObject.put("relation", value3);
return contactObject;
}
so your jsonobjects are ready for sending we write these objects to ServletoutputStream.
in client side-
while ((ReadResponses = in.readLine()) != null) {
Constants.Response_From_server = ReadResponses;
if (Constants.Response_From_server.startsWith("{")) {
ListOfContactStatus = new ArrayList<ContactStatus>();
ContactStatus contactStatusObject;
try {
JSONObject json = new JSONObject(Constants.Response_From_server);
for (int i = 0; i < json.length(); i++) {
contactStatusObject = new ContactStatus();
JSONObject json1 = json.getJSONObject(String.valueOf(i));
System.out.println("" + json1.getString("id"));
System.out.println("" + json1.getBoolean("status"));
System.out.println("" + json1.getDouble("distance"));
contactStatusObject.setId(json1.getString("id"));
contactStatusObject.setStatus(json1.getBoolean("status"));
contactStatusObject.setDistance((float) json1.getDouble("distance"));
ListOfContactStatus.add(contactStatusObject);
System.out.println("HTTPTransport:sendMessage Size of ListOfContactStatus" + ListOfContactStatus.size());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
You can easily generate JSonObject usin Java EE 7. The sample code.
JsonReader reader = Json.createReader(new URI(url, true));
JsonObject jsonObject=reader.readObject();
For details information go through to the link.
http://docs.oracle.com/javaee/7/tutorial/doc/jsonp003.htm#BABHAHIA
In the android app I get an xml or json string returned, However, I cant seem to figure out any way on how to get an value from the string in any way by entering an key.
In PHP you just use something like $myArray['parent']['child'] but I have no clue on how this works in java.
Any idea's would be greatly appreciated! (an example for both XML and JSON even more ;) )
Here's what I would do:
locate an XML/JSON library (there's tons) (google-gson for json)
read the documentation to find a parse method ((new JsonParser()).parse(text))
read the documentation to find out what the return value is (JsonElement)
decide what you want to do with the parsed data (myJsonObj.get(...))
write the code
public class parsingjsontest2 extends Activity {
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(main);
String str = connect("http://rentopoly.com/ajax.php?query=Bo"));
System.out.println("String::"+str);
}
}
private String connect(String url)
{
// Create the httpclient
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
// return string
String returnString = null;
try {
// Open the webpage.
response = httpclient.execute(httpget);
if(response.getStatusLine().getStatusCode() == 200){
// Connection was established. Get the content.
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
// Load the requested page converted to a string into a JSONObject.
JSONObject myAwway = new JSONObject(convertStreamToString(instream));
// Get the query value'
String query = myAwway.getString("query");
**// Make array of the suggestions
JSONArray suggestions = myAwway.getJSONArray("suggestions");
// Build the return string.
returnString = "Found: " + suggestions.length() + " locations for " + query;
for (int i = 0; i < suggestions.length(); i++) {
returnString += "\n\t" + suggestions.getString(i);
}
// Cose the stream.
instream.close();
}
}
else {
// code here for a response othet than 200. A response 200 means the webpage was ok
// Other codes include 404 - not found, 301 - redirect etc...
// Display the response line.
returnString = "Unable to load page - " + response.getStatusLine();
}
}
catch (IOException ex) {
// thrown by line 80 - getContent();
// Connection was not established
returnString = "Connection failed; " + ex.getMessage();
}
catch (JSONException ex){
// JSON errors
returnString = "JSON failed; " + ex.getMessage();
}
return returnString;
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
As you didn't specify what kind of xml you are trying to read, I'm answering based on what I know.
In Android, if you were talking about the layout and strings.xml files, you use a dot (.) operator, like R.string.appname.
Please post more details about your specific problem, if this is not what you were looking for.