mak_doni
mak_doni

Reputation: 581

How to fill an array from jsonArray dynamically in java

I have a JSON structure as given below:

{  
   "success":1,
   "message":"facture found",
   "factures":[  
      {  
         "mois_fact":"May17",
         "nbr_fact":"1"
      },
      {  
         "mois_fact":"Jun17",
         "nbr_fact":"2"
      },
      {  
         "mois_fact":"Jun16",
         "nbr_fact":"1"
      }
   ]
}

I want to create two arrays, the first contains the values of the key mois_fact and the second conains the values of nbr_fact, I tried this attempt with just one array absisse and I had this result :

value mois 1
value mois 1
value mois 1
value mois 2
value mois 2
value mois 2
value mois 1
value mois 1
value mois 1

My attempt :

String[] absisse = new String[3]; 
JSONArray factures= json.getJSONArray("factures");
for (int i = 0; i < factures.length(); i++) {
JSONObject c = factures.getJSONObject(i);
int nbr = c.getString("nbr_fact");
 for(int z=0;z<absisse.length;z++){
absisse[z]=nbr;
System.out.println("value mois "+absisse[z]);
}
}

Upvotes: 1

Views: 1544

Answers (1)

GensaGames
GensaGames

Reputation: 5788

         /*
         * List of your nbr_fact objects
         */
        List<String> nbr_fact_objects= new ArrayList<>();
         /*
         * List of your mois_fact objects
         */
        List<String> mois_fact_objects= new ArrayList<>();

        JSONArray factures= json.getJSONArray("factures");
        for (int i = 0; i < factures.length(); i++) {
            JSONObject c = factures.getJSONObject(i);

            String nbr = c.getString("nbr_fact");
            if (nbr != null) {
                nbr_fact_objects.add(nbr);
            }
            String mois = c.getString("mois_fact");
            if (mois != null) {
                mois_fact_objects.add(mois);
            }

        }

Upvotes: 1

Related Questions