在将Web服务与SQLite同步时,会出现数组和对象错误

时间:2017-05-15 04:20:31

标签: android json web-services sqlite

我正在尝试将我的json数据导入我的sqlite,从Web服务到android。

这是我开始同步时遇到的错误。

error stating Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

错误出现在这段代码上。

 public String processSync(String response) {
    String status = FAILED;
    try {
        String formattedData = getFormattedData(response);
        final GsonBuilder gsonBuilder = new GsonBuilder();
        final Gson gson = gsonBuilder.create();
        ProductDataBean[] productDataBeanArray = gson.fromJson(formattedData, ProductDataBean[].class);
        AdministratorHelper administratorHelper = new AdministratorHelper();
        status = administratorHelper.insertProductData(context, productDataBeanArray);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return status;
}

AdministratorHelper.java

public class AdministratorHelper {

DBLiteUtils dbLiteUtils;
AdministratorDao dao = new AdministratorDao();

public String insertProductData(Context context, ProductDataBean[] productDataBeanArray){
    String status = FAILED;
    try{
        dbLiteUtils = new DBLiteUtils(context);
        dbLiteUtils.open();
        status = dao.insertProductData(dbLiteUtils, productDataBeanArray);
    } catch (Exception e){
        e.printStackTrace();
    } finally {
        dbLiteUtils.close();
    }
    return status;
}

AdministratorDao.java

public class AdministratorDao {

private Cursor cursor;

//Insert Product Details into SQLite
public String insertProductData(DBLiteUtils dbLiteUtils, ProductDataBean[] productDataBeanArray){
    String status = FAILED;
    try {
        if(productDataBeanArray.length > 0) {
            //Delete Existing Data
            dbLiteUtils.deleteAll("ProductMaster");

            //Base Insert Query for inserting New Data into ProductMaster Table
            String query = "INSERT INTO ProductMaster(ItemId, Description, Barcode, TransStatusCode) VALUES ";
            //Iterate the productDataBeanArray in order to get productDataBean which contains a single product details
            for (ProductDataBean productDataBean : productDataBeanArray) {
                //Concatenate the Base Insert Query and the product details
                query = query+"('"+productDataBean.getItemId().trim()+"', '"+productDataBean.getDescription().trim().replace("\'", "\'\'")+"', '"+productDataBean.getBarcode().trim()+"', '"+productDataBean.getTransStatusCode().trim()+"'),"; //.trim() removes unwanted empty spaces
            }
            //Remove the last comma from the iterated complete query
            query = query.substring(0, query.length()-1);
            //execute the query
            dbLiteUtils.executeQuery(query);
            //return  success
            status = SUCCESS;
        }
    } catch (Exception e){
        e.printStackTrace();
    }
    return status;
}

这是我在visual studio中获取json数据的代码

 public class ProductController : ApiController
{

    public IEnumerable<Product> Get()
    {
        List<Product> pproducts;
        using (estocktakeEntities entities = new estocktakeEntities())
        {

            pproducts = entities.Products.ToList();
            //return entities.products.ToList();

        }
        return pproducts;

    }

这是我的json的样本

  

[{“invtid”:“02007997”,“ib_itemcode1”:“0”,“transtatuscode”:“IN”,“descr”:“潘婷C / C重症护理面膜6 x 150m”},   {“invtid”:“1”,“ib_itemcode1”:“1”,“transtatuscode”:“IN”,“descr”:“object1”},{“invtid”:“13101336”,“ib_itemcode1”:“47400179172” ,“transtatuscode”:“IN”,“descr”:“Gillette Mach 3 Dispenser 8S(X12)”},   {“invtid”:“13101473”,“ib_itemcode1”:“47400179349”,“transtatuscode”:“IN”,“descr”:“Gillette Mach3 Cart 4S(X12)

如果需要更多信息,请告诉我,我将非常愿意上传它们。

先生,谢谢你的时间。

编辑1

尝试调试后,我遇到了这个错误,仍然不确定是否有用,但这里是错误和与之相关的代码。

  

{“Message”:“发生了错误。”,“ExceptionMessage”:“值不能为空。\ r \ nParameter name:entity”,“ExceptionType”:“System.ArgumentNullException”,“StackTrace”:“在System.Data.Entity.Utilities.Check.NotNull [T](T值,字符串parameterName)\ r \ n在System.Data.Entity.DbSet`1.Add(TEntity实体)\ r \ n在ProductServiceFinal.Controllers .ProductController.Post(Product productrecord)“}

ProductController.Post

   public HttpResponseMessage Post([FromBody] Product productrecord)
    {
        try
        {
            using (estocktakeEntities entities = new estocktakeEntities())
            {
                entities.Products.Add(productrecord);
                //entities.Entry(productrecord).State = System.Data.Entity.EntityState.Modified;

                entities.SaveChanges();

                var message = Request.CreateResponse(HttpStatusCode.Created, productrecord);
                message.Headers.Location = new Uri(Request.RequestUri + productrecord.invtid.ToString());
                return message;
            }

        }
        catch (Exception ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
        }
    }

1 个答案:

答案 0 :(得分:0)

错误日志是:com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column所以我猜问题是JSON主体是提供的Web服务。

 public String processSync(String response) {
    String status = FAILED;
    try {
        String formattedData = getFormattedData(response);
        final GsonBuilder gsonBuilder = new GsonBuilder();
        final Gson gson = gsonBuilder.create();
        ProductDataBean[] productDataBeanArray = gson.fromJson(formattedData, ProductDataBean[].class);
        AdministratorHelper administratorHelper = new AdministratorHelper();
        status = administratorHelper.insertProductData(context, productDataBeanArray);
    } catch (Exception e) {
        Log.e("tag",formattedData); // log out this JSON
        e.printStackTrace();
    }
    return status;
}

EDIT 1告诉我,Web服务可能会出现问题。 (我猜Web服务返回错误的JSON) 我的建议是添加一些“容错”#34;代码到Android项目。
根本原因可能在Web服务中。