JSON 错误 "java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $"
JSON Error "java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $"
public interface UserService {
@POST(Constants.Api.URL_REGISTRATION)
@FormUrlEncoded
BaseWrapper registerUser(@Field("first_name") String firstname, @Field("last_name") String lastname, @Field("regNumber") String phone, @Field("regRole") int role);
public BaseWrapper registerUser(User user) {
return getUserService().registerUser(user.getFirstName(), user.getLastName(), user.getPhone(), user.getRole());
}
这会创建异常
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
非常感谢您的帮助。
让我们看看您收到的错误。
Expected BEGIN_OBJECT
您的 JSON 是一个对象,所有 JSON 对象都用大括号 ({}) 括起来。 BEGIN_OBJECT 因此是 {.它在某处期待它。
but was STRING
但他却找到了一个字符串 "Something"。仍然没有告诉我们在哪里。
at line 1 column 1 path $
啊,完美。在第 1 行第 1 列。这是 JSON 的开始。所以您忘记了将整个内容包含在 {} 中(或者至少您忘记了第一个,但我打赌您两个都忘记了)。
清理并重建项目
这是由于 Gson 文件有些混乱造成的。
清理和重建项目对我有用。
如果你想在 json 对象中添加 ArrayList 并在 GSON 中解析然后确保 ArrayList 应该如下所示。
ArrayList<JSONObject>
而不是
ArrayList<String>
并像这样解析。
ArrayList<JSONObject> mItem = new ArrayList<JSONObject>();
mItem.add(jsonObject);
// and Use like this.
JSONArray list = new JSONArray(mItem);
jsonObject.put("Item",list);
最近我遇到了类似的问题,只能通过将 "Accept: application/json" 添加到 header 部分来解决。所以,如果您使用的是改造 2.0;
第一个解决方案: 对于 post 方法添加 headers 参数,如下所示;
@Headers({"Accept: application/json"})
@POST(Constants.Api.URL_REGISTRATION)
@FormUrlEncoded
BaseWrapper registerUser(@Field("first_name") String firstname,
@Field("last_name") String lastname,
@Field("regNumber") String phone,
@Field("regRole") int role);
第二个解决方案:像这样将header添加到你的拦截器class中;
注意:代码在 kotlin 中
private fun getInterceptor(): Interceptor {
try {
return Interceptor {
val request = it.request()
it.proceed(
request.newBuilder()
.header("Accept", "application/json")
.header("Authorization", "$accessTokenType $accessToken")
.build()
)
}
} catch (exception: Exception) {
throw Exception(exception.message)
}
}
}
希望对您有所帮助,编码愉快:)
如果您的应用使用之前版本的存储数据,而您更改了数据类型,则可能会遇到此错误。
例如:我在以前的版本中将一些东西存储为字符串。我后来将存储数据的 class 更新为对象类型。当我 运行 它时,我得到了这个错误。清除应用数据或重新安装后,错误清除。
清除应用程序数据可能是一个简单的解决方法。
解决方案
在 Kotlin 中,我们可以使用 ResponseBody 的 Response 并在其中管理初始响应。
viewModelScope.launch(Dispatchers.IO) {
mainRepository.getAPIData(
Constants.getRequestBody(requestBody.toString())
).let { it ->
if (it.isSuccessful && it.code() == 200) {
val responseBody = it.body()
val res: String? = responseBody?.string()
try {
val main = JSONObject(res!!)
Log.e("TAG", "onSuccess: " + main.toString())
if (main.getInt("StatusCode") == 200) {
val type = object : TypeToken<Response>() {}.type
val response: Response = Gson().fromJson(
main.toString(), type
)
Log.e("TAG", "onSuccess: " + response.toString())
} else {
apiResponseData.postValue(Resource.error(main.getString("Message"), null))
Log.e("TAG", "onFail: " + main.toString())
}
} catch (exception: JSONException) {
Log.e("TAG", "Exception: " + exception.message)
}
}
}
}
响应 - 改造
ResponseBody - okHttp
Response 是实际模型 Response 例如用户响应
这里getAPIData()是API调用ResponseBodyreturnsResponse
apiResponseData 是 MutableLiveData
使用它可以避免响应中的 JSON 类型转换错误。
这是一个混淆器问题。在版本中 minifyEnabled true 破坏了 API 模型。
您需要在 ResponseModel 和 RequestModel API
中添加 Serializable
https://i.stack.imgur.com/uHN22.png
public interface UserService {
@POST(Constants.Api.URL_REGISTRATION)
@FormUrlEncoded
BaseWrapper registerUser(@Field("first_name") String firstname, @Field("last_name") String lastname, @Field("regNumber") String phone, @Field("regRole") int role);
public BaseWrapper registerUser(User user) {
return getUserService().registerUser(user.getFirstName(), user.getLastName(), user.getPhone(), user.getRole());
}
这会创建异常
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
非常感谢您的帮助。
让我们看看您收到的错误。
Expected BEGIN_OBJECT
您的 JSON 是一个对象,所有 JSON 对象都用大括号 ({}) 括起来。 BEGIN_OBJECT 因此是 {.它在某处期待它。
but was STRING
但他却找到了一个字符串 "Something"。仍然没有告诉我们在哪里。
at line 1 column 1 path $
啊,完美。在第 1 行第 1 列。这是 JSON 的开始。所以您忘记了将整个内容包含在 {} 中(或者至少您忘记了第一个,但我打赌您两个都忘记了)。
清理并重建项目 这是由于 Gson 文件有些混乱造成的。
清理和重建项目对我有用。
如果你想在 json 对象中添加 ArrayList 并在 GSON 中解析然后确保 ArrayList 应该如下所示。
ArrayList<JSONObject>
而不是
ArrayList<String>
并像这样解析。
ArrayList<JSONObject> mItem = new ArrayList<JSONObject>();
mItem.add(jsonObject);
// and Use like this.
JSONArray list = new JSONArray(mItem);
jsonObject.put("Item",list);
最近我遇到了类似的问题,只能通过将 "Accept: application/json" 添加到 header 部分来解决。所以,如果您使用的是改造 2.0;
第一个解决方案: 对于 post 方法添加 headers 参数,如下所示;
@Headers({"Accept: application/json"})
@POST(Constants.Api.URL_REGISTRATION)
@FormUrlEncoded
BaseWrapper registerUser(@Field("first_name") String firstname,
@Field("last_name") String lastname,
@Field("regNumber") String phone,
@Field("regRole") int role);
第二个解决方案:像这样将header添加到你的拦截器class中;
注意:代码在 kotlin 中
private fun getInterceptor(): Interceptor {
try {
return Interceptor {
val request = it.request()
it.proceed(
request.newBuilder()
.header("Accept", "application/json")
.header("Authorization", "$accessTokenType $accessToken")
.build()
)
}
} catch (exception: Exception) {
throw Exception(exception.message)
}
}
}
希望对您有所帮助,编码愉快:)
如果您的应用使用之前版本的存储数据,而您更改了数据类型,则可能会遇到此错误。
例如:我在以前的版本中将一些东西存储为字符串。我后来将存储数据的 class 更新为对象类型。当我 运行 它时,我得到了这个错误。清除应用数据或重新安装后,错误清除。
清除应用程序数据可能是一个简单的解决方法。
解决方案
在 Kotlin 中,我们可以使用 ResponseBody 的 Response 并在其中管理初始响应。
viewModelScope.launch(Dispatchers.IO) {
mainRepository.getAPIData(
Constants.getRequestBody(requestBody.toString())
).let { it ->
if (it.isSuccessful && it.code() == 200) {
val responseBody = it.body()
val res: String? = responseBody?.string()
try {
val main = JSONObject(res!!)
Log.e("TAG", "onSuccess: " + main.toString())
if (main.getInt("StatusCode") == 200) {
val type = object : TypeToken<Response>() {}.type
val response: Response = Gson().fromJson(
main.toString(), type
)
Log.e("TAG", "onSuccess: " + response.toString())
} else {
apiResponseData.postValue(Resource.error(main.getString("Message"), null))
Log.e("TAG", "onFail: " + main.toString())
}
} catch (exception: JSONException) {
Log.e("TAG", "Exception: " + exception.message)
}
}
}
}
响应 - 改造
ResponseBody - okHttp
Response 是实际模型 Response 例如用户响应
这里getAPIData()是API调用ResponseBodyreturnsResponse
apiResponseData 是 MutableLiveData
使用它可以避免响应中的 JSON 类型转换错误。
这是一个混淆器问题。在版本中 minifyEnabled true 破坏了 API 模型。 您需要在 ResponseModel 和 RequestModel API
中添加 Serializablehttps://i.stack.imgur.com/uHN22.png