【问题标题】:com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 2 column 2 path $com.google.gson.stream.MalformedJsonException:使用 JsonReader.setLenient(true) 在第 2 行第 2 列路径 $ 接受格式错误的 JSON
【发布时间】:2019-12-26 05:31:41
【问题描述】:

在登录时出现此错误,如果您知道任何解决方案,请不要降级,请指导我。我还检查了不同的堆栈溢出帖子,但他们都在谈论通过改造来修剪字符串或其他解决方案,但我无法解决它。我使用截击。

我的 Json 文件:-

{
  "error": false,
  "user": [
    {
      "user_id": "123",
      "customer_name": "Abc",
      "email": "abc@example.com",
      "salt": "123abc",
      "phone": "1234567890",
      "address": "Enter Address",
      "postal_code": "1234"
    }
  ]
}

这是我的 Java 类:-

@Override
    protected String doInBackground(Boolean... booleen) {
        ExampleApi exampleApi = new ExampleApi();
        LoginUser result;
        try {
            result = exampleApi.loginPost(sharedPreferences.getString("abc_id", ""), semail, fcmToken, spassword);
            Gson gson = new Gson();                           
            String json = gson.toJson(result);
            JSONObject jObj = new JSONObject(json);
            Log.e("result1", String.valueOf(jObj));
            if (jObj.getString("error").equalsIgnoreCase("false")) {
                JSONArray jsonArray = jObj.getJSONArray("user");
                JSONObject jsonObject1 = jsonArray.getJSONObject(0);
                 return "true";
                 }else {
                String errormsg = jObj.getString("error_msg");
                return errormsg;
            }
            } catch (ApiException e) {
            e.printStackTrace();
            Log.e("error", e.toString());
        } catch (JSONException e) {
            e.printStackTrace();
            }
            }

【问题讨论】:

  • 你可以编辑问题并发布LoginUser类。
  • 需要调查loginPostLoginUser。你能添加这些吗?
  • 我也使用这种方式,但它也不起作用:- Gson gson = new Gson();字符串结果1 = String.valueOf(result); JsonReader reader = new JsonReader(new StringReader(result1)); reader.setLenient(true); String json = gson.fromJson(reader, UserInfo.class); JSONObject jObj = new JSONObject(json);
  • 能贴出错误日志吗?
  • E/error: com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: 使用 JsonReader.setLenient(true) 在第 2 行第 2 列路径 $ @Sajith 接受格式错误的 JSON

标签: android api android-volley malformed


【解决方案1】:

你可以尝试如下初始化 Gson

Gson gson = new GsonBuilder()
        .setLenient()
        .create();

预期的 JSON 中可能存在问题。

【讨论】:

  • 响应内容类型可能存在问题。应该是application/json
  • 感谢您的回复,但它已经是 application/json ("accept: application/json") @Vir Rajpurohit
【解决方案2】:

检查user对象(user_id, customer_name. etc)的属性是否与作为响应接收到的对象格式正确。

ps:如果user_id 在您的user 对象中是一个Integer,它也应该是一个Integer

【讨论】:

    【解决方案3】:

    在我的例子中,这个错误是由于非 UTF-8 json 文件编码而产生的。当我将它转换为 UTF-8 时,一切都开始工作了。

    【讨论】:

      猜你喜欢
      • 2017-02-16
      • 2017-06-03
      • 2018-08-25
      • 1970-01-01
      • 1970-01-01
      • 2018-06-24
      • 1970-01-01
      • 2020-02-08
      • 2018-05-17
      相关资源
      最近更新 更多