Creating JSONArray inside other JSONArray? - arrays

I have two classes Sale and ItemSale. I'm trying create a JSONArray with all objects of Sale and add all ItemSale in this JSONArray. The problem is I don't know how I can do it.
I need this: Sale:{id:1, data:2015-09-28, cliente_id:1}, ItemSale:[{produto:5, quantidade:10, valorUnitario:5.00, totalItem:50.00}], Sale:{id:2, data:2015-09-28, cliente_id:33}, ItemSale:[{produto:10, quantidade:1, valorUnitario:5.00, totalItem:5.00}, {produto:23, quantidade:1, valorUnitario:10.00, totalItem:10.00}, {produto:25, quantidade:1, valorUnitario:20.00, totalItem:20.00}]
I'm trying this.
private JSONObject getJSONObjectToSend(){
JSONObject jsonVendas = new JSONObject();
JSONArray jsonArrayVenda = new JSONArray();
JSONArray jsonArrayItems = new JSONArray();
VendaPersist vp = new VendaPersist(getActivity());
//list of sale
List<Sale> lista = vp.getAllVendasFinalizadas();
try {
if(lista.size() > 0){
for(Sale v : lista){
JSONObject jsonObjectVenda = new JSONObject();
//Sale
jsonObjectVenda.put("dataVenda", new SimpleDateFormat("yyyy-MM-dd").format(v.getDataVenda()));
jsonObjectVenda.put("cliente", v.getCliente().getId_ws());
jsonObjectVenda.put("usuario", v.getIdUsuario());
jsonArrayVenda.put(jsonObjectVenda);
//itens Sale
for(ItemSale iv : v.getListaItems()){
JSONObject jsonObjectIV = new JSONObject();
jsonObjectIV.put("produto", iv.getProduto().getId_ws());
jsonObjectIV.put("quantidade", iv.getQuantidade());
jsonObjectIV.put("valorUnitario", iv.getValorUnitario());
jsonObjectIV.put("valorTotal", iv.getTotalItem());
jsonArrayItems.put(jsonObjectIV);
}
jsonArrayVenda.put(jsonArrayItems);
jsonVendas.put("Sale", jsonArrayVenda);
}
}
} catch (JSONException e) {
Log.e(TAG, e.getLocalizedMessage());
}
return jsonVendas;
}

You are not constructing a JSONArray but a JSONObject.
JSONArray jsonArr = new JSONArray();
jsonArr.put(jsonVendas);

Related

Android: Parsing JSON. No value for...?

I am trying to parse JSON data generated by an API.Here is the json I am trying to parse:
{
"response":{
"legislator":[
{
"#attributes":{
"cid":"N00033987",
"firstlast":"Doug LaMalfa",
"lastname":"LAMALFA",
"party":"R",
"office":"CA01",
"gender":"M",
"first_elected":"2012",
"exit_code":"0",
"comments":"",
"phone":"202-225-3076",
"fax":"530-534-7800",
"website":"http:\/\/lamalfa.house.gov",
"webform":"https:\/\/lamalfa.house.gov\/contact\/email-me",
"congress_office":"322 Cannon House Office Building",
"bioguide_id":"L000578",
"votesmart_id":"29713",
"feccandid":"H2CA02142",
"twitter_id":"RepLaMalfa",
"youtube_url":"https:\/\/youtube.com\/RepLaMalfa",
"facebook_id":"RepLaMalfa",
"birthdate":"1960-07-02"
}
The response json object inside of the entire response is throwing me off. I cant get to the legislator array. The logcat gives me this error:
How can I modify my method to get to the legislator json array?
Here is my parsing method:
private void getData() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject responseObj = jsonObject.getJSONObject("response");
JSONArray array = responseObj.getJSONArray("legislator");
for(int i = 0; i < array.length(); i++){
JSONObject attributesObj = array.getJSONObject(i);
//create object
Legs leg = new Legs(attributesObj.getString("firstlast"),
attributesObj.getString("party"),
attributesObj.getString("office"),
attributesObj.getString("gender"),
attributesObj.getString("birthdate"),
attributesObj.getString("first_elected"),
attributesObj.getString("phone"),
attributesObj.getString("website"),
attributesObj.getString("congress_office"),
attributesObj.getString("twitter_id"),
attributesObj.getString("youtube_url"),
attributesObj.getString("facebook_id"));
legList.add(leg);
}
adapter = new LegRvAdapter(Legislators.this, legList);
myrv.setAdapter(adapter);
}catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("Volley", volleyError.toString());
progressDialog.dismiss();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}

Split the string array

I know this question was absolutely answered but i did not find solution.
I get response from web-service a Json string response that is ["11,22222","33,44444"].
I try this but did not work because string include these characters [ ] and first comma is in the here 11,22
StringBuilder result = new StringBuilder();
URL url2 = new URL(url);
HttpURLConnection conn = (HttpURLConnection) url2.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
String res = new String(result);
String [] coordinates = res.split(",");
How can i separate this string like "11,22222" and "33,44444"
Just use JavaScriptSerializer.
public void Method(string json)
{
JavaScriptSerializer js = new JavaScriptSerializer();
List<string> results = js.Deserialize<List<string>>(json);
}
JsonArray jArray=new JsonArray(result);
StringBuffer s=new StringBuffer();
for(int i=0;i<jArray.length();i++)
{
s.append(jArray.getString(i));
Log.e(“singleValue”,jArray.getString(i));
}
Log.e(“responsed”,s.toString());
Since you are getting a json, you can easily convert it to JsonArray and iterate thorugh it.
Gson gson = new Gson();
JsonArray array = gson.fromJson(rd, JsonElement.class).getAsJsonArray();
for (JsonElement jsonElement : array) {
System.out.println(jsonElement.getAsString());
}
Hope this helps.

Convert JSONArray to Object?

I have the following JSON and I want to create an Contact object from it. How we can do that using
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
</dependency>
Here is the String
{"totalSize":1,"done":true,"records":[{"attributes":{"type":"Contact","url":"/services/data/v40.0/sobjects/Contact/0037F000001rW9rQAE"},"Id":"0037F000001rW9rQAE","Name":"Chris Smith"}]}
I developed below code but how how to used JSONArray to get the details from it ?
JSONParser jsonParser = new JSONParser();
Object obj = jsonParser.parse(value);
JSONObject jsonObject = (JSONObject) obj;
JSONArray jsonArray = (JSONArray) jsonObject.get("records");
System.out.println("~~~~~~~~~~~>>> "+jsonArray);
List<Contact> contacts = new ArrayList<>();
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject rec = (JSONObject) jsonArray.get(i);
Contact c = new Contact();
c.setId(jsonArray.get(j).toString());
contacts.add(jsonArray.get(j).toString());
}
You can solve your issue like this but if you want to manage exceptions you should use the method getString(KEY), instead optString(KEY)
List<Contact> contacts = new ArrayList<>();
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject rec = (JSONObject) jsonArray.get(i);
Contact c = new Contact();
c.setId(rec.optString("Id"));
c.setName(rec.optString("Name"));
c.setAtributes(rec.optJSONObject("attributes"))
contacts.add(rec);
}

Getting data from JSONObject in JSONArray from JSONObject

{"location":{
"name":"New York","region":"New York","country":"United States of America","lat":40.71,"lon":-74.01,"tz_id":"America/New_York","localtime_epoch":1488124171,"localtime":"2017-02-26 10:49"},
"forecast":{
"forecastday":[{"date":"2017-02-26","date_epoch":1488067200,"day":{"maxtemp_c":5.2,"mintemp_c":1.0,"avgtemp_c":3.5,"maxwind_kph":28.1,
"astro":{"sunrise":"06:34 AM",...
I am programming a Weather App, but when I want to access the, for Example, date then Android Studio says that there is : No value for forecast. This is how I try to get the data:
JSONObject jsonObject = new JSONObject(data);
[...]
JSONObject forecastObject = Utils.getObject("forecast", jsonObject);
JSONArray forecastArray = forecastObject.getJSONArray("forecastday");
JSONObject forecastWeather = forecastArray.getJSONObject(0);
weather.currentCondition.setDate(Utils.getString("date", forecastWeather));
JSONObject dayObject = Utils.getObject("day", forecastWeather);
What am I doing wrong?? Can You help me?
Are you sure, that you want item at index 0 of this JSONArray? To get JSONArray from JSONObject, you call JSONArray array = object.getJSONArray("key"), then JSONObject newobject = array.getJSONObject(index).
public static Weather getWeather(String data){
Weather weather = new Weather();
//creat JSONObject from data
try {
JSONObject jsonObject = new JSONObject(data);
Place place = new Place();
JSONObject locationObject = Utils.getObject("location", jsonObject);
place.setLat(Utils.getFloat("lat", locationObject));
place.setLon(Utils.getFloat("lon", locationObject));
place.setCity(Utils.getString("name", locationObject));
place.setCountry(Utils.getString("country", locationObject));
place.setRegion(Utils.getString("region", locationObject));
place.setLocaltime(Utils.getString("localtime", locationObject));
weather.place=place;
JSONObject currentObject = Utils.getObject("current", jsonObject);
weather.currentCondition.setLastupdated(Utils.getString("last_updated", currentObject));
weather.currentCondition.setTemperature(Utils.getString("temp_c", currentObject));
weather.currentCondition.setWindkph(Utils.getString("wind_kph", currentObject));
weather.currentCondition.setHumidity(Utils.getFloat("humidity", currentObject));
weather.currentCondition.setCloud(Utils.getInt("cloud", currentObject));
weather.currentCondition.setFeelslike(Utils.getDouble("feelslike_c", currentObject));
weather.wind.setWinddir(Utils.getString("wind_dir", currentObject));
weather.currentCondition.setPreciption(Utils.getString("precip_mm", currentObject));
weather.currentCondition.setPressure(Utils.getFloat("pressure_mb", currentObject));
JSONObject iconObject = Utils.getObject("condition", currentObject);
weather.currentCondition.setIcon(Utils.getString("icon", iconObject));
weather.currentCondition.setDescription(Utils.getString("text", iconObject));
return weather;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
This is the function of how i get my data from the website apixu.com
This is how i connect:
public class WeatherHttpClient {
public String getWeatherData(String place){
HttpURLConnection connection = null;
InputStream inputStream = null;
try {
connection = (HttpURLConnection) (new URL(Utils.BASE_URL + place)).openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setDoInput(true);
connection.connect();
//Read response
StringBuffer stringBuffer = new StringBuffer();
inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while((line = bufferedReader.readLine())!=null){
stringBuffer.append(line+ "\r\n");
}
inputStream.close();
connection.disconnect();
return stringBuffer.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}

android app development-passing parameter to database

I am trying to connect my app to database on localhost server.I can connect to it ut the problem is how to pass the parameter from app to php script.for eg i want all names having age less than 10 so i will pass the parameter to php.below is my code for connecting to database.please provide good reference
/* */
enter code here
public class TestExternalDatabaseActivity extends Activity {
/** Called when the activity is first created. */
TextView resultView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StrictMode.enableDefaults(); //STRICT MODE ENABLED
resultView = (TextView) findViewById(R.id.result);
getData();
}
public void getData(){
String result = "";
InputStream isr = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/tahseen0amin/php/getAllCustomers.php"); //YOUR PHP SCRIPT ADDRESS
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
}
catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
resultView.setText("Couldnt connect to database");
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try {
String s = "";
JSONArray jArray = new JSONArray(result);
for(int i=0; i<jArray.length();i++){
JSONObject json = jArray.getJSONObject(i);
s = s +
"Name : "+json.getString("FirstName")+" "+json.getString("LastName")+"\n"+
"Age : "+json.getInt("Age")+"\n"+
"Mobile Using : "+json.getString("Mobile")+"\n\n";
}
resultView.setText(s);
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data "+e.toString());
}
}
}

Resources