only last row of arraylist being saved in JSON object - java

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

Related

Get specific value from JSON array using java

I want to fetch only PersonNumber value from below JSON sample using java.
{"Context":[{"PersonNumber":"10","DMLOperation":"UPDATE","PeriodType":"E","PersonName":"Ponce","WorkerType":"EMP","PersonId":"1000","PrimaryPhoneNumber":"1","EffectiveStartDate":"2018-01-27","EffectiveDate":"2018-01-27"}],"Changed Attributes":[{"NamInformation1":{"new":"Ponce","old":"PONCE"}},{"FirstName":{"new":"Jorge","old":"JORGE"}},{"LastName":{"new":"Ponce","old":"PONCE"}}]}
Below is my code:
for (SyndContentImpl content : (List<SyndContentImpl>) entry.getContents()) {
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(content.getValue().toString());
System.out.println(jsonObj.get("Context"));
} catch (JSONException e) {
e.printStackTrace();
} }
You have to access to the path Context[0].PersonNumber.
This can be done with
String personNumber = jsonObj.getJSONArray("Context").getJSONObject(0).getString("PersonNumber");

Getting JSON values from a .json

I am currently writing a program that pulls weather info from openweathermaps api. It returns a JSON string such as this:
{"coord":{"lon":-95.94,"lat":41.26},"weather":[{"id":500,"main":"Rain","description":"light
rain","icon":"10n"}],"base":"stations","main": ...more json
I have this method below which writes the string to a .json and allows me to get the values from it.
public String readJSON() {
JSONParser parse = new JSONParser();
String ret = "";
try {
FileReader reader = new FileReader("C:\\Users\\mattm\\Desktop\\Java Libs\\JSON.json");
Object obj = parse.parse(reader);
JSONObject Jobj = (JSONObject) obj;
System.out.println(Jobj.get("weather"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(ret);
return ret;
}
The problem is it only allows me to get the outer values such as "coord" and "weather". So currently since I have System.out.println(Jobj.get("weather")); it will return [{"icon":"10n","description":"light rain","main":"Rain","id":500}] but I want to actually get the values that are inside of that like the description value and the main value. I haven't worked much with JSONs so there may be something obvious I am missing. Any ideas on how I would do this?
You can use JsonPath (https://github.com/json-path/JsonPath) to extract some json field/values directly.
var json = "{\"coord\":{\"lon\":\"-95.94\",\"lat\":\"41.26\"},\n" +
" \"weather\":[{\"id\":\"500\",\"main\":\"Rain\",\"description\":\"light\"}]}";
var main = JsonPath.read(json, "$.weather[0].main"); // Rain
you can use
JSONObject Jobj = (JSONObject) obj;
System.out.println(Jobj.getJSONObject("coord").get("lon");//here coord is json object
System.out.println(Jobj.getJSONArray("weather").get(0).get("description");//for array
or you can declare user defined class according to structure and convert code using GSON
Gson gson= new Gson();
MyWeatherClass weather= gson.fromJSON(Jobj .toString(),MyWeatherClass.class);
System.out.println(weather.getCoord());
From the json sample that you have provided it can be seen that the "weather" actually is an array of objects, so you will have to treat it as such in code to get individual objects from the array when converted to Jsonobject.
Try something like :
public String readJSON() {
JSONParser parse = new JSONParser();
String ret = "";
try {
FileReader reader = new FileReader("C:\\Users\\mattm\\Desktop\\Java Libs\\JSON.json");
Object obj = parse.parse(reader);
JSONObject jobj = (JSONObject) obj;
JSONArray jobjWeatherArray = jobj.getJSONArray("weather")
for (int i = 0; i < jobjWeatherArray.length(); i++) {
JSONObject jobjWeather = jobjWeatherArray.getJSONObject(i);
System.out.println(jobjWeather.get("id"));
System.out.println(jobjWeather.get("main"));
System.out.println(jobjWeather.get("description"));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(ret);
return ret;
}

Get List<GraphUser> from executeAndWait() for Facebook integration on Android

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

HTTPResponse as JSON in Java

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

I can't read data from JSON

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!

Categories

Resources