我一直在寻找解决方案来解决这个问题,但我似乎无法找到解决方案。我获得的JSON数据格式与我发现的其他示例不同。
这是我从php(在Web服务器中)获得的JSON数据的示例:
{"cols":[
{"label":"time","type":"datetime"},
{"label":"Temperature","type":"number"}],
"rows":[
{"c":[{"v":"Date(2014, 9, 14, 14, 8, 50)"},{"v":23.02}]},
{"c":[{"v":"Date(2014, 9, 14, 14, 12, 1)"},{"v":23.02}]},
{"c":[{"v":"Date(2014, 9, 14, 14, 12, 3)"},{"v":23.02}]},
{"c":[{"v":"Date(2014, 9, 14, 14, 12, 5)"},{"v":23.02}]},
{"c":[{"v":"Date(2014, 9, 14, 14, 12, 7)"},{"v":22.54}]},
...
我不是创建该PHP文件的人,我无法从中更改任何内容。
我尝试使用JSONParser,就像所有示例一样,但它不起作用。如何解析数据并将其显示在ListView上?
答案 0 :(得分:0)
您可以尝试类似以下内容:
public String getDataString() {
String someString = "";
JSONObject jsonObj = getData();
Log.i("JSON string =>", jsonObj.toString());
String text= null;
try {
// Handle cols
JSONArray cols = jsonObj.getJSONArray("cols");
int i = 0;
Log.i("i", i+ "," + cols.length() ); //TODO delete this
while(i<cols.length()) {
JSONObject obj= cols.getJSONObject(i);
String labelType = obj.getString("label");
if(labelType.equals("time"))
{
text = obj.getString("datetime");
}
else if(labelType.equals("Temperature"))
{
text = obj.getString("number");
}
// Do something with String text
i++;
}
// Handle rows
JSONArray rows= jsonObj.getJSONArray("rows");
int i = 0;
Log.i("i", i+ "," + rows.length() ); //TODO delete this
while(i<rows.length()) {
JSONObject obj= rows.getJSONObject(i);
JSONArray cObj= obj.getJSONArray("c");
JSONObject vFirst = cObj.getJSONObject(0);
JSONObject vSecond = cObj.getJSONObject(1);
String firstString = vFirst.getString("v");
String secondString = vSecond .getString("v");
// Do something with String firstString and/or String secondString
i++;
}
}
} catch (JSONException e) {
Log.e("testing","Failed to load JSON");
e.printStackTrace();
}
.
.
.
// Return some string
return someString;
.
.
.
}
public static JSONObject getData() {
HttpGet httpGet = new HttpGet("YOUR_URI_HERE");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();
try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
答案 1 :(得分:0)
您可以使用谷歌的Gson库将JSON对象直接解析为Java对象。