使用gson错误转换json预期的BEGIN_OBJECT,但是BEGIN_ARRAY在第1行第2列路径$ [英] converting json with gson error Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
本文介绍了使用gson错误转换json预期的BEGIN_OBJECT,但是BEGIN_ARRAY在第1行第2列路径$的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
[{"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,但遇到错误。
I'm trying to convert the JSON above with GSON but am running into errors.
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();
}
}
}
该网址和api键都是空白的,出于安全原因,当我运行代码并将json正确转换为字符串时,变量被填充。我已经测试过了。如果有人能告诉我是什么原因导致了错误,那将是美好的。
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.
package com.grapefruitcode.osu;
public class User {
String user_id = "";
String username = "";
String count300 = "";
String count100= "";
}
推荐答案
在JSON中
-
[...]
表示数组
{...}
表示对象,
[ ... ]
represents array{ ... }
represents object,
so [{...}]
是包含一个对象的数组。尝试使用
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]);
这篇关于使用gson错误转换json预期的BEGIN_OBJECT,但是BEGIN_ARRAY在第1行第2列路径$的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文