1

i know this is repeated question and there are many similar questions, but the answers was unclear for me, my problem is how to convert Arraylist of object (in my case it is array list of class product given below) i have a class called product:

public class Product extends AppCompatActivity implements Serializable {
    public String product_name;
    public String product_barcode;
    public String product_price;
    public String product_qty;
    public String total;
    public String cat_name;
    public int pos;
    public String actualPrice;


    // setter and getter 


}

i want to convert the Arraylist to json format to send it to php script that adds the ArrayList to MySQL using volley, i tried to use GSON but i think there is wrong because when is sending it the php script does not recognize it, here is my method for GSON:

public void toMySQL (){
        Gson g = new Gson();
      test_Json=  g.toJson(arr);
    }

what i want the data is as following format:

[  
   {  
     "product_name": "Water",  
     "product_price": "1",  
     "product_qty": "12"  
   },  
   {  
     "product_name": "Pepsi",  
     "product_price": "3",  
     "product_qty": "15"  
   },  
   {  
     "product_name": "SevenUP",  
     "product_price": "3",  
     "product_qty": "12"  
   },  

   {  
     "product_name": "cola",  
     "product_price": "3",  
     "product_qty": "24"  
   }
 ]

Any help?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Katio
  • 29
  • 1
  • You expect only 3 fields of `Product` in your json but you are not telling `Gson` to do that. Take a look at [this](https://stackoverflow.com/questions/4802887/gson-how-to-exclude-specific-fields-from-serialization-without-annotations) and [this](https://stackoverflow.com/questions/40909205/java-gson-exclude-fields-during-serialization) – szamani20 Oct 20 '17 at 20:54
  • Possible duplicate of [Java Gson Exclude fields during serialization](https://stackoverflow.com/questions/40909205/java-gson-exclude-fields-during-serialization) – szamani20 Oct 20 '17 at 20:56

1 Answers1

1

You can try

      JSONArray list = new JSONArray(arr);
      String product = gson.toJson(list,
       new TypeToken<ArrayList<Product>>() {}.getType());
Ankit Aman
  • 999
  • 6
  • 15