我有以下JSON结构(github api response https://api.github.com/users/vGrynishyn/repos)
[
{
"id": 102121086,
"name": "DolynaPlus",
"full_name": "vGrynishyn_DolynaPlus",
"owner": {
"login": "vGrynishyn",
"id": 26795358,
............
},
"private": false,
"html_url": "https://github.com/vGrynishyn/DolynaPlus",
"description": null,
..............
},
{
"id": 103648881,
"name": "GoogleSearchMaven",
"full_name": "vGrynishyn/GoogleSearchMaven",
"owner": {
"login": "vGrynishyn",
"id": 26795358,
.........
},
"private": false,
"html_url": "https://github.com/vGrynishyn/GoogleSearchMaven",
"description": null,
...................
}
]
我尝试了以下代码来获取数组并收到异常 - 无法转换为数组
JSONArray jsonArray = new JSONArray(json_response);
我试过杰克逊解析它,但我不需要结果。 我只收到了第一部分的结果,并且出现了异常
JsonFactory fac = new JsonFactory();
JsonParser jp = null;
jp = fac.createParser(json_response);
StringBuilder strPar = new StringBuilder(" ");
jp.nextValue();
while(jp.nextValue() != JsonToken.END_ARRAY){
while (jp.nextToken() != JsonToken.END_OBJECT) {
String fieldName = jp.getCurrentName();
jp.nextToken();
if (fieldName.equals("id")){
strPar.append(jp.getText()+"; ");
}else if (fieldName.equals("name")){
strPar.append(jp.getText()+"; ");
}else if (fieldName.equals("full_name")){
strPar.append(jp.getText()+"; ");
}
}
}
我如何解析它。请帮忙。
答案 0 :(得分:1)
以下代码可以正常使用:
public class JSONParse {
public static void main(String[] args) throws Exception {
String url = "https://api.github.com/users/vGrynishyn/repos";
String data = readUrl(url);
JSONArray jsonArr = new JSONArray(data);
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
System.out.println(jsonObj.get("name"));
}
}
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();
}
}
}
输出:
DolynaPlus
GoogleSearchMaven
GoogleTesting
RadioTakt
Testlibrary
答案 1 :(得分:0)
从错误消息中可以看出,您的JSON可能具有不正确的字符。 (您发布的JSON也不是有效的JSON)
请发布实际的JSON,也许我可以进一步提供帮助:)