android中使用JAVA解析json数据
发布网友
发布时间:2022-05-27 18:47
我来回答
共2个回答
热心网友
时间:2023-11-18 05:34
这个格式使用如下代码解析
try {
JSONObject jsonObject = new JSONObject(json);
JSONObject weatherinfo = jsonObject.getJSONObject("weatherinfo");
System.out.println(weatherinfo.getString("city"));
System.out.println(weatherinfo.getString("cityid"));
System.out.println(weatherinfo.getString("temp"));
System.out.println(weatherinfo.getString("WD"));
} catch (JSONException e) {
e.printStackTrace();
}
其中第一行代码 JSONObject jsonObject = new JSONObject(json);//json 即为你的字符串
比如现在天气信息是多个城市的,并非只有北京市。
{"weatherinfo":[{"city":"北京","cityid":"101010100","temp":"4","WD":"东风","WS":"2级","SD":"75%","WSE":"2","time":"10:45","isRadar":"1","Radar":"JC_RADAR_AZ9010_JB","njd":"暂无实况","qy":"1011"},{"city":"天津","cityid":"101010100","temp":"4","WD":"东风","WS":"2级","SD":"75%","WSE":"2","time":"10:45","isRadar":"1","Radar":"JC_RADAR_AZ9010_JB","njd":"暂无实况","qy":"1011"}]}
以下代码适用。
try {
JSONObject jsonObject=new JSONObject(json);
JSONArray jsonArray=jsonObject.getJSONArray("weatherinfo");
for (int i=0;i<jsonArray.length();i++){
JSONObject object = jsonArray.getJSONObject(i);
System.out.println(object.getString("city"));
System.out.println(object.getString("cityid"));
System.out.println(object.getString("temp"));
System.out.println(object.getString("WD"));
}
} catch (JSONException e) {
e.printStackTrace();
}
热心网友
时间:2023-11-18 05:34
import org.json.JSONException;
import org.json.JSONObject;
public class test {
/**
* @param args
*/
public static void main(String[] args) {
String s = "{\"weatherinfo\":{\"city\":\"北京\",\"cityid\":\"101010100\",\"temp\":\"4\",\"WD\":\"东风\",\"WS\":\"2级\",\"SD\":\"75%\",\"WSE\":\"2\",\"time\":\"10:45\",\"isRadar\":\"1\",\"Radar\":\"JC_RADAR_AZ9010_JB\",\"njd\":\"暂无实况\",\"qy\":\"1011\"}}";
try {
JSONObject jsonObject = new JSONObject(s);
JSONObject json = (JSONObject) jsonObject.get("weatherinfo");
System.out.println(json.getString("city"));
System.out.println(json.getInt("temp"));
System.out.println(json.getString("WD"));
System.out.println(json.getString("WS"));
System.out.println(json.getString("SD"));
System.out.println(json.getInt("WSE"));
System.out.println(json.getString("time"));
System.out.println(json.getString("isRadar"));
System.out.println(json.getString("Radar"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}