我可以连接到服务器并获取json数据。它采用以下格式:
{"clazz":"ManiaContestantList","contestants":[
{"clazz":"ManiaContestant","contestantId":"1","contestantName":"Adira","photoUrl":"/fileFeed.action?service=astroManiaService&action=viewFile&type=JPG&path=1/1_CONTESTANT_PHOTO.png"},
{"clazz":"ManiaContestant","contestantId":"2","contestantName":"Akim","photoUrl":"/fileFeed.action?service=astroManiaService&action=viewFile&type=JPG&path=2/2_CONTESTANT_PHOTO.png"},
.
.
.
]}
我的代码是这样的:
@Override
protected void onStart() {
super.onStart();
Log.i("NewsList", "inside onStart();");
try {
URL url = new URL("/MY URL/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(Manager.ConnTimeout);
conn.setReadTimeout(Manager.ReadTimeout);
int responseCode = conn.getResponseCode();
Log.i("Connection oppened", "Response code is:" + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
if (in != null) {
StringBuilder strBuilder = new StringBuilder();
// Read character by character
int ch = 0;
while ((ch = in.read()) != -1)
strBuilder.append((char) ch);
// get returned message and show it
strServerResponseMsg = strBuilder.toString();
Log.i("Data returned by server:", strServerResponseMsg);
JSONArray jObjects = new JSONArray(strServerResponseMsg);
for(int i=0; i<jObjects.length(); i++){
System.out.println(jObjects.getJSONObject(i).getString("contestantId").toString());
System.out.println(jObjects.getJSONObject(i).getString("contestantName").toString());
System.out.println(jObjects.getJSONObject(i).getString("photoUrl").toString());
}
in.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
我在“strServerResponseMsg”变量中回复了Json。但是在“JSONArray jObjects = new JSONArray(strServerResponseMsg);
”行中,Logcat显示typemismatch
错误。
请告诉我我的问题是什么?
答案 0 :(得分:4)
{
表示它是一个对象。 [
表示它是一个数组。因为你的字符串以{
开头,所以它是一个JSONObject而不是JSONArray。
JSONArray jObjects = new JSONArray(strServerResponseMsg);
必须像这样
JSONObject jObjects = new JSONObject(strServerResponseMsg);
答案 1 :(得分:1)
给出的json示例不是jsonarray它是一个jsonobject所以你应该像下面这样的东西
JSONObject jObj = new JSONObject(strServerResponseMsg);
JSONArray jArray = new JSONArray(jObj.getJSONArray("contestants"));
然后遍历jArray
答案 2 :(得分:0)
这是一个JSONObject,你可以看到&#39; {&#39 ;.
JSONObject j=null;
try{
j=new JSONObject(strServerResponseMsg);
}
catch(JSONException r)
{
//Handle it.
r.printStackTrace();
}
Log.w("json",j.toString());
答案 3 :(得分:0)
JSON已经过时,如果你使用json,你必须非常小心处理。 所以,使用谷歌开发的GSON api。它是在json api的帮助下完成的。 请访问此链接 - Click here