【问题标题】:How can I convert Arraylist<Product> to JSON?如何将 Arraylist<Product> 转换为 JSON?
【发布时间】:2017-10-20 20:50:51
【问题描述】:

我知道这是重复的问题,并且有很多类似的问题,但我不清楚答案,我的问题是如何转换对象的 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 格式以将其发送到 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"  
   }
 ]

有什么帮助吗?

【问题讨论】:

标签: android json arraylist


【解决方案1】:

你可以试试

      JSONArray list = new JSONArray(arr);
      String product = gson.toJson(list,
       new TypeToken<ArrayList<Product>>() {}.getType());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-15
    • 2014-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-08
    • 1970-01-01
    相关资源
    最近更新 更多