我使用 moshi 将 JSon 解析为 Object 。这是我的 JSon:
[{
"id": 4,
"phone": {
"id": 3,
"imei": "356938035643801",
"description": "Marek Kowalski"
},
"user": {
"id": 3,
"username": "marek.kowalski",
"first_name": "Marek",
"last_name": "Kowalski"
},
"user_id": 3,
"message": "Podejrzane zachowanie, sprawd??.",
"date_time_data": "2017-09-05T22:26:44.916927Z",
"longitude": 19.934113,
"latitude": 50.075086,
"confirm": 0,
"changetime": "2017-09-05T22:26:44.930357Z",
"has_coordinates": 1
}]
Run Code Online (Sandbox Code Playgroud)
这是我的对象:
public class Message {
String message;
double longitude;
double latitude;
int confirm;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public int getConfirm() {
return confirm;
}
public void setConfirm(int confirm) {
this.confirm = confirm;
}
}
Run Code Online (Sandbox Code Playgroud)
我这样做是为了将 JSON 解析为 obecjt :
Message message = App.getMsg().fromJson(new String(responseBody, "UTF-8"));
Run Code Online (Sandbox Code Playgroud)
但是我的应用程序崩溃了,在日志中我看到了这个:
检测到用户空间异常!com.squareup.moshi.JsonDataException:预期为 BEGIN_OBJECT,但在路径 $ 处为 BEGIN_ARRAY,位于 com.squareup.moshi.BufferedSourceJsonReader.beginObject(BufferedSourceJsonReader.java:171) 在 com.squareup.moshi.ClassJsonAdapter.fromJson(ClassJsonAdapter.java:14)在 com.squareup.moshi.JsonAdapter$1.fromJson(JsonAdapter.java:68) 在 com.squareup.moshi.JsonAdapter.fromJson(JsonAdapter.java:33) 在 com.squareup.moshi.JsonAdapter.fromJson(JsonAdapter.
问题是,你所要求的一个Message对象,但你确实有一个数组的Message对象。尝试这样做:
String jsonResponseBody = ...;
Type type = Types.newParameterizedType(List.class, Message.class);
JsonAdapter<List<Message>> adapter = moshi.adapter(type);
List<Message> messages = adapter.fromJson(jsonResponseBody);
Run Code Online (Sandbox Code Playgroud)