在我的应用程序中,我以Json格式发送base64编码文件。我的代码是:
JSONObject jsonRequest = prepareJsonObject(expense, contentUri);
String jsonString = jsonRequest.toString();
StringEntity se = new StringEntity(jsonString);
jsonRequest对象如下所示:
{
"category":"660",
"user":"458",
"dated_on":"Wed Mar 12 10:38:11 GMT+00:00 2014",
"description":"document",
"gross_value":"-2.0",
"currency":"GBP",
"attachment":{
"data":"<base64>"
"mimetype":"image/jpeg"
}
}
问题是jsonRequest.toString()
对于700Kb文件需要2分钟。
有没有办法让这个更快?我做错了吗?
感谢。
编辑:我正在测试运行KITKAT的实际Nexus 4。为了完成目的,这是prepareJsonObject()的代码,它在不到2秒的时间内运行。
public static JSONObject prepareJsonObject(Expense expense, String contentUri){
JSONObject expenseJson = null;
try{
expenseJson = new JSONObject();
if(expense.getUserId()!=null) expenseJson.put("user", expense.getUserId().toString());
if(expense.getProjectId()!=null) expenseJson.put("project", expense.getProjectId().toString());
if(expense.getCurrency()!=null) expenseJson.put("currency", expense.getCurrency().toString());
if(expense.getGrossValue()!=null) expenseJson.put("gross_value", expense.getGrossValue().toString());
if(expense.getNativeGrossValue()!=null) expenseJson.put("native_gross_value", expense.getNativeGrossValue().toString());
if(expense.getSalesTaxRate()!=null) expenseJson.put("sales_tax_rate", expense.getSalesTaxRate().toString());
if(expense.getDescription()!=null)expenseJson.put("description", expense.getDescription().toString());
if(expense.getDated()!=null)expenseJson.put("dated_on", expense.getDated());
if(expense.getCategoryId()!=null) expenseJson.put("category", expense.getCategoryId().toString());
if(expense.getManualSalesTaxAmount()!=null)expenseJson.put("manual_sales_tax_amount", expense.getManualSalesTaxAmount().toString());
if(contentUri!=null){
JSONObject attachmentJson = new JSONObject();
String base64data = AttachmentsUtils.getBase64ForUri(Uri.parse(contentUri));
attachmentJson.put("data", base64data);
attachmentJson.put("content_type", AttachmentsUtils.getMimetypeFromContentUri(Uri.parse(contentUri)));
expenseJson.put("attachment", attachmentJson);
}
}catch(Exception e){
Log.e("ExpensesUtils", "Couldn't encode attachment: "+e.getLocalizedMessage());
return null;
}
return expenseJson;
}
答案 0 :(得分:1)
我认为这是因为toString
削减了base64数据的全部内容来处理unicode字符并转义某些特定字符。您可以在JSONStringer#string中看到这一点,当您致电toString
时,JsonObject会调用每个字符串值。
当然,由于您的数据是base64,您实际上并不需要这样做。所以我认为你需要实现自己的toString实现,可能基于JSONStringer
而没有转义