Android 如何转换Arraylist<;产品>;到JSON?

Android 如何转换Arraylist<;产品>;到JSON?,android,json,arraylist,Android,Json,Arraylist,我知道这是一个重复的问题,也有许多类似的问题,但答案对我来说并不清楚,我的问题是如何转换对象的Arraylist(在我的例子中,它是下面给出的类产品的数组列表)我有一个名为product的类: public class Product extends AppCompatActivity implements Serializable { public String product_name; public String product_barcode; public St

我知道这是一个重复的问题,也有许多类似的问题,但答案对我来说并不清楚,我的问题是如何转换对象的Arraylist(在我的例子中,它是下面给出的类产品的数组列表)我有一个名为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 


}
我想将Arraylist转换为json格式,将其发送到php脚本,该脚本使用volley将Arraylist添加到MySQL,我尝试使用GSON,但我认为这是错误的,因为在发送它时,php脚本无法识别它,下面是我对GSON的方法:

public void toMySQL (){
        Gson g = new Gson();
      test_Json=  g.toJson(arr);
    }
我需要的数据格式如下:

[  
   {  
     "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"  
   }
 ]
有什么帮助吗?

你可以试试

      JSONArray list = new JSONArray(arr);
      String product = gson.toJson(list,
       new TypeToken<ArrayList<Product>>() {}.getType());
JSONArray列表=新的JSONArray(arr);
字符串product=gson.toJson(列表,
新的TypeToken(){}.getType());

您希望json中只有3个
Product
字段,但您并没有要求
Gson
这样做。查看和可能的副本