将JSONArray字符串值转换为int值

时间:2018-08-03 18:42:21

标签: android arrays json

我需要将键“ Quantity”中的值转换为整数。

基本上我有这个:

   ALTER PROCEDURE [dci].[webDonorStatistics] @FiscalYear INT
   AS
   BEGIN
    --DECLARE @FiscalYear INT = 2018

   DECLARE
   @StartDate DATE = CONVERT(DATE, '01-OCT-' + CONVERT(CHAR(4), @FiscalYear - 1))
   , @EndDate DATE = DATEADD(DAY, -1, GETDATE())

   IF @EndDate >= CONVERT(DATE, '30-SEP-' + CONVERT(CHAR(4), @FiscalYear))
    SELECT @EndDate = CONVERT(DATE, '30-SEP-' + CONVERT(CHAR(4), @FiscalYear))
    ELSE
     SELECT @EndDate = DATEADD(DAY, -1, CONVERT(DATE, '01-' + DATENAME(MONTH, GETDATE()) + '-' + CONVERT(CHAR(4), YEAR(GETDATE()))))  -- End of previous month

    IF DATEDIFF(DAY, @StartDate, @EndDate) < 0
    SELECT @EndDate = GETDATE()

    BEGIN TRY
     DROP TABLE #webDonorStatistics
    END TRY
    BEGIN CATCH
    END CATCH

需要转换为此:

[{"Code":"NV","Quantity":"333"},{"Code":"NV","Quantity":"333"}]

我该怎么办?

2 个答案:

答案 0 :(得分:1)

假设您的json数据为字符串形式,并将其设置为data字符串

String data = "[{\"Code\":\"NV\",\"Quantity\":\"333\"},{\"Code\":\"NV\",\"Quantity\":\"333\"}]";

try {
    JSONArray jsonArray = new JSONArray(data);
    Log.d(TAG, "Old JSONArray: " + jsonArray); // [{"Code":"NV","Quantity":"333"},{"Code":"NV","Quantity":"333"}]

    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject jsonObject = (JSONObject) jsonArray.get(i);
        int quantityValue = Integer.parseInt(jsonObject.getString("Quantity"));
        jsonObject.put("Quantity", quantityValue);
    }
    Log.d(TAG, "New JSONArray: " + jsonArray); // [{"Code":"NV","Quantity":333},{"Code":"NV","Quantity":333}]

} catch (JSONException e) {
    e.printStackTrace();
}

我在这里所做的只是通过使用Quantitystring值替换旧的int Integer.parseInt()

答案 1 :(得分:0)

请尝试以下操作:

for(int i = 0; i < array.length(); i++){
    JSONObject object = array.getJSONObject(i); 
    object.put("Quantity", Integer.parseInt(object.getString("Quantity")));
}

您需要用阵列名称替换array