[{"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":[]}]
我正在尝试使用 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();
}
}
}
出于安全原因,url 和 api key 留空,当我运行代码时变量被填充并且 json 被正确转换为字符串。我已经测试过了。如果有人能告诉我是什么导致了错误,那就太好了。
package com.grapefruitcode.osu;
public class User {
String user_id = "";
String username = "";
String count300 = "";
String count100= "";
}
最佳答案
在 JSON 中
[ ... ]
代表数组{ ... }
代表对象,
所以 [ {...} ]
是包含一个对象的数组。尝试使用
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]);
关于java - 使用 gson 错误转换 json 预期为 BEGIN_OBJECT 但在第 1 行第 2 列路径 $ 处为 BEGIN_ARRAY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28295116/