'JsonSyntaxException:com.google.gson.stream.MalformedJsonException:第1行第30列的未终止对象”

时间:2019-10-15 18:22:51

标签: java json

我的API响应如下:

[
{
    "id": "123",
    "date": "2016-12-11T12:23:34Z",
    "description": "A bag of spanners",
    "amount": "35.25",
    "currency": "GBP"
},
{
    "id": "124",
    "date": "2016-12-12T01:58:59Z",
    "description": "Hot chocholate",
    "amount": "12.50",
    "currency": "GBP"
},
{
    "id": "125",
    "date": "2016-12-12T06:11:06Z",
    "description": "Subscriptions - Magazine",
    "amount": "5.99",
    "currency": "GBP"
},
{
    "id": "126",
    "date": "2016-12-13T10:03:17Z",
    "description": "Movie rental",
    "amount": "3.99",
    "currency": "GBP"
}]

我尝试使用Java来解析它,如下所示:

            Object object = (Object) HttpRequest.getInputStreamFromUrl(ApiUtils.getTransactionsUrl(), Object.class, mContext);
            Type typeMyType = new TypeToken<ArrayList<Transaction>>(){}.getType();
            Gson gson = new Gson();
            transactionList = gson.fromJson(object.toString(), typeMyType);

我得到'JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 column 30'

我还尝试了其他一些方法,这些方法导致了com.google.gson.internal.LinkedTreeMap cannot be cast to org.json.JSONObject

如何解析这种JSON对象?

1 个答案:

答案 0 :(得分:0)

我能够通过将InputStream转换为String而不是Object来解决此问题。我使用一种方法将InputStream直接转换为Object。但这似乎有时不起作用。我使用以下方法将InputStream转换为String

    public static String convertStreamToString(HttpResponse response) {
    String responseBody = null;
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        try {
            responseBody = EntityUtils.toString(entity);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return responseBody;
}

然后将返回的String转换为List,如下所示:

            String responseStr = (String) HttpRequest.getInputStreamFromUrl(ApiUtils.getTransactionsUrl(), mContext);
            Type typeMyType = new TypeToken<ArrayList<Transaction>>(){}.getType();
            Gson gson = new Gson();
            transactionList = gson.fromJson(responseStr.toString(), typeMyType);

希望它可以帮助遇到相同问题的人。