Java解析json格式的字符串,jar包和源码参见附件,该jar包也是从网上找到的。
示例代码:
public class JsonTest {
public static void main(String[] args) {
parseJsonWithOrgJson();
}
public static void parseJsonWithOrgJson(){
try {
String jsonString = "{\"Image\":{\"Width\":800,\"Height\":600,\"Title\":\"View from 15th Floor\",\"Thumbnail\":{\"Url\":\"http://www.example.com/image/481989943\",\"Height\":125,\"Width\":\"100\"},\"IDs\":[116, 943, 234, 38793]}}";
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject jsonObjectImage = jsonObject.getJSONObject("Image");
int width = jsonObjectImage.getInt("Width");
int height = jsonObjectImage.getInt("Height");
String title = jsonObjectImage.getString("Title");
System.out.println("WIDTH:" + width);
System.out.println("HEIGHT:" + height);
System.out.println("TITLE:" + title);
JSONObject jsonObjectTHU = jsonObjectImage.getJSONObject("Thumbnail");
String url = jsonObjectTHU.getString("Url");
int width2 = jsonObjectTHU.getInt("Width");
int height2 = jsonObjectTHU.getInt("Height");
System.out.println("URL:" + url);
System.out.println("WIDTH2:" + width2);
System.out.println("HEIGHT2:" + height2);
JSONArray jsonArrayIDS = jsonObjectImage.getJSONArray("IDs");
for(int i=0;i<jsonArrayIDS.length();i++){
System.out.println("数组" + i + ":" + jsonArrayIDS.getInt(i));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
从源码中可以看到,对于json里存储的对象是放在map容器里的,数组是放在List容器里的。
源码和jar的下载地址http://download.csdn.net/detail/h407210874/7622913