不多说废话了,直奔主题,我将java类中解析json分为两种情况:
情况一:
[{"name":"测试","index":"555","count":141}]
如果你要解析的json是这样的格式,java中做这样的处理:
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
String json = "[{"name":"咖啡","remak":"进口咖啡","count":141}]";
JSONArray job = JSONArray.fromObject(json);
for(int i = 0;i < job.size(); i++){
JSONObject jsonObject = job.getJSONObject(i);
int count = (int) jsonObject.get("count");
}
情况二:
{"cityInfo":[{"cityId":"01","cityName":"南京"},{"cityId":"02","cityName":"无锡"}],"proName":"江苏省"}
如果json是这样的格式,java中这样处理:
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
String json = "{\"cityInfo\":[{\"cityId\":\"01\",\"cityName\":\"南京\"},{\"cityId\":\"02\",\"cityName\":\"无锡\"}],\"proName\":\"江苏省\"}";
JSONObject obj = new JSONObject(json.toString());
JSONArray obj2 = obj.getJSONArray("cityInfo");
for (int i = 0; i < obj2.length(); i++) {
JSONObject temp = new JSONObject(obj2.getString(i));
System.out.println(temp.getString("cityId"));
System.out.println(temp.getString("cityName"));
}
System.out.println("所在省份:"+obj.getString("name"));
// 2016-07-21 些许地方更正:如果在java类中直接写一个 json(如上面例子中所示)的话,需要用转义字符将"给转义一下,具体如下(留一个没改正的,作比较^_^~~):
String json = "[{\"name\":\"咖啡\",\"remak\":\"进口咖啡\",\"count\":141}]";
没有写类,但是把导包的代码粘贴出来了,只是提醒一下不要忘记导包 ^_^~~~