作业帮 > 综合 > 作业

json-lib解析json数据

来源:学生作业帮 编辑:作业帮 分类:综合作业 时间:2024/05/16 18:06:44
json-lib解析json数据
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
public class Getjson
{
\x05public void main(String []args)
\x05{
\x05\x05 String json = "{'name':'亲亲宝宝','array':[{'a':'111','b':'222','c':'333'},{},{'a':'999'}],'address':'亲亲宝宝'}";
\x05\x05 try
\x05\x05 {
\x05\x05 \x05JSONObject jsonObject = JSONObject.fromObject(json);
\x05\x05 \x05String name = jsonObject.getString("name");
\x05\x05 \x05String address = jsonObject.getString("address");
\x05\x05 \x05System.out.println("name is:" + name);
\x05\x05 \x05System.out.println("address is:" + address);
\x05\x05 \x05JSONArray jsonArray = jsonObject.getJSONArray("array");
\x05\x05 \x05for (int i = 0; i < jsonArray.size(); i++)
\x05\x05 \x05{
\x05\x05 \x05 System.out.println("item" + i + ":" + jsonArray.getString(i));
\x05\x05 \x05}
\x05\x05 } catch (JSONException e)
\x05\x05 {
\x05\x05 e.printStackTrace();
\x05\x05 }
}
}
我想知道为什么用json-lib解析上面的json数据没有反映.
public class GetJson {
\x05public static void main(String[] args) {//main方法写错了哈.掉了static
\x05\x05String json = "{'name': '亲亲宝宝','array':[{'a':'111','b':'222','c':'333'},{},{'a':'999'}],'address':'亲亲宝宝'}";
\x05\x05try {
\x05\x05\x05JSONObject jsonObject = JSONObject.fromObject(json);
\x05\x05\x05String name = jsonObject.getString("name");
\x05\x05\x05String address = jsonObject.getString("address");
\x05\x05\x05System.out.println("name is:" + name);
\x05\x05\x05System.out.println("address is:" + address);
\x05\x05\x05JSONArray jsonArray = jsonObject.getJSONArray("array");
\x05\x05\x05for (int i = 0; i < jsonArray.size(); i++) {
\x05\x05\x05\x05System.out.println("item" + i + ":" + jsonArray.getString(i));
\x05\x05\x05}
\x05\x05} catch (JSONException e) {
\x05\x05\x05e.printStackTrace();
\x05\x05}
\x05}
}
修改了main方法就可以了
再问: 哈哈,我真是笨死了,这么低级的错误 ,我就说 怎么没有反映,谢谢你啊呵呵