android - 如何将 Arraylist<Product> 转换为 JSON?

标签 android json arraylist

我知道这是重复的问题并且有很多类似的问题,但我的答案不清楚,我的问题是如何转换对象的数组列表(在我的例子中它是下面给出的类产品的数组列表)我有一个称为产品的类:

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 格式以将其发送到使用 volley 将 ArrayList 添加到 MySQL 的 php 脚本,我尝试使用 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());

关于android - 如何将 Arraylist<Product> 转换为 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46857153/

相关文章:

.net - 如何从 VBA 查找 .net ArrayList 中的文字数字?

java.lang.UnsupportedOperationException 但没有 Arrays.asList()

json - 使用 jq 对 JSON 进行分组和计数

java - 如何从java中的数组中读取一行中包含多个元素的多行?

android - 无法让 TextView 在对话框中填充 ListView 中的父级高度

android - 没有网络连接时如何调用新布局?

java - Spring REST 调用在浏览器中显示 JSON——有没有办法允许用户下载文件?

c# - 将 JSON 数据从 Web 映射到 .NET 类,其中数据因每个 API 请求而异

java - 从 Adapter 中刷新整个 RecyclerView

android - 为什么我的 Android 单元测试一起运行时失败,但单独运行时通过?