java 使用gson错误转换json 预期为BEGIN_OBJECT,但在第1行第2列路径$为BEGIN_ARRAY
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28295116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
converting json with gson error Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
提问by Alex Markovich
[{"user_id":"5633795","username":"_Vorago_","count300":"203483","count100":"16021","count50":"1517","playcount":"1634","ranked_score":"179618425","total_score":"1394180836","pp_rank":"34054","level":"59.6052","pp_raw":"1723.43","accuracy":"96.77945709228516","count_rank_ss":"1","count_rank_s":"19","count_rank_a":"17","country":"US","events":[]}]
I'm trying to convert the JSON above with GSON but am running into errors.
我正在尝试使用 GSON 转换上面的 JSON,但遇到了错误。
package com.grapefruitcode.osu;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import com.google.gson.Gson;
public class Main {
static String ApiKey = "";
public static void main(String[]Args) throws Exception{
String json = readUrl("");
System.out.println(json);
Gson gson = new Gson();
User user = gson.fromJson(json, User.class);
System.out.println();
}
private static String readUrl(String urlString) throws Exception {
BufferedReader reader = null;
try {
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
return buffer.toString();
} finally {
if (reader != null)
reader.close();
}
}
}
The url and api key are left blank for security reasons, the variables are filled when I run the code and the json is converted to a string properly. I've tested it already. If somebody could tell me what is causing the error that would be wonderful.
出于安全原因,url 和 api 密钥留空,当我运行代码时填充变量,并且 json 正确转换为字符串。我已经测试过了。如果有人能告诉我是什么导致了错误,那就太好了。
package com.grapefruitcode.osu;
public class User {
String user_id = "";
String username = "";
String count300 = "";
String count100= "";
}
回答by Pshemo
In JSON
在 JSON 中
[ ... ]
represents array{ ... }
represents object,
[ ... ]
代表数组{ ... }
代表对象,
so [ {...} ]
is array containing one object. Try using
[ {...} ]
包含一个对象的数组也是如此。尝试使用
Gson gson = new Gson();
User[] users = gson.fromJson(json, User[].class);
System.out.println(Arrays.toString(users));
//or since we know which object from array we want to print
System.out.println(users[0]);
回答by Keshav Gera
Using RetroFit 2 Solution
使用 RetroFit 2 解决方案
interface APIInterface {
@POST("GetDataController/GetData")
Call<GeoEvent> getGeofanceRecord(@Body GeoEvent geoEvent);
}
APIInterface apiInterface; // Declare Globally
apiInterface = APIClient.getClient().create(APIInterface.class);
final GeoEvent geoEvent = new GeoEvent(userId);
Call<GeoEvent> call = apiInterface.getGeofanceRecord(geoEvent);
call.enqueue(new Callback<GeoEvent>() {
@Override
public void onResponse(Call<GeoEvent> call, Response<GeoEvent> response) {
GeoEvent geoEvent1 = response.body();
// Log.e("keshav","Location -> " +geoEvent1.responseMessage);
List<GeoEvent.GeoEvents> geoEventsList = geoEvent1.Table; // Array Naame
List<GeoEvent.GeoEvents> geoEventsArrayList = new ArrayList<GeoEvent.GeoEvents>();
geoEventsArrayList.addAll(geoEventsList);
for (GeoEvent.GeoEvents geoEvents : geoEventsList) {
Log.e("keshav", "Location -> " + geoEvents.Location);
Log.e("keshav", "DateTime -> " + geoEvents.DateTime);
}
if (geoEventsArrayList != null) {
adapter.clear();
adapter.addAll(geoEventsArrayList);
adapter.notifyDataSetChanged();
}
}
@Override
public void onFailure(Call<GeoEvent> call, Throwable t) {
call.cancel();
}
});
Your Pojo Class Like This
你的 Pojo 类像这样
package pojos;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
public class GeoEvent {
public String userId;
public GeoEvent(String userId){
this.userId= userId;
}
public List<GeoEvents> Table = new ArrayList<>();
public class GeoEvents {
@SerializedName("Location")
public String Location;
@SerializedName("DateTime")
public String DateTime;
public String getLocation() {
return Location;
}
public void setLocation(String location) {
Location = location;
}
public String getDateTime() {
return DateTime;
}
public void setDateTime(String dateTime) {
DateTime = dateTime;
}
}
}