java解析json实例,java 与json应用举例说明。
package wzq.j2se;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonDemo {
static String json1 = “[{ "id ":1, "login_password ": "nnnnnn ", "login_acct ": "lixueming "},{ "id ":2, "login_password ": "zzzzzz ", "login_acct ": "liyun "},{ "id ":3, "login_password ": "zzzzzz ", "login_acct ": "wzq1987 "}] “;
static String json2 = “{ “programmers “: [ { "firstName ": "Brett ", "lastName ": "McLaughlin ", "email ": "aaaa " },"+
"{ "firstName ": "Jason ", "lastName ": "Hunter ", "email ": "bbbb " },"+
"{ "firstName ": "Elliotte ", "lastName ": "Harold ", "email ": "cccc " }"+
"],”+
” “authors “: ["+
"{ "firstName ": "Isaac ", "lastName ": "Asimov ", "genre ": "science fiction " },"+
"{ "firstName ": "Tad ", "lastName ": "Williams ", "genre ": "fantasy " },"+
"{ "firstName ": "Frank ", "lastName ": "Peretti ", "genre ": "christian fiction " }"+
"],”+
” “musicians “: ["+
"{ "firstName ": "Eric ", "lastName ": "Clapton ", "instrument ": "guitar " },"+
"{ "firstName ": "Sergei ", "lastName ": "Rachmaninoff ", "instrument ": "piano " }"+
"] }”;
/**
* @param args
*/
public static void main(String[] args) {
three();
}
public static void json2list(){
try{
JSONArray arry = new JSONArray(json1);
List> rsList = new ArrayList>();
for (int i = 0; i < arry.length(); i++)
{
JSONObject jsonObject = arry.getJSONObject(i);
Map map = new HashMap();
for (Iterator> iter = jsonObject.keys(); iter.hasNext();)
{
String key = (String) iter.next();
String value = jsonObject.get(key).toString();
map.put(key, value);
}
rsList.add(map);
}
System.out.println(“rsList==”+rsList);
}catch(Exception e){
e.printStackTrace();
}
}
public static void three(){
try{
JSONObject jsonObject = new JSONObject(json2);
for(Iterator iter = jsonObject.keys(); iter.hasNext();){
String key = (String)iter.next();
JSONArray arry = new JSONArray(jsonObject.get(key).toString());
for (int i = 0; i < arry.length(); i++){
JSONObject jsonList = arry.getJSONObject(i);
for (Iterator> iterlist = jsonList.keys(); iterlist.hasNext();)
{
String mkey = (String) iterlist.next();
Object mvalue = jsonList.get(mkey);
System.out.println(mkey+”:”+mvalue);
}
System.out.println(“”);
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}
重点看three()这个方法,先把JSON按OBJECT取出来,也就是JSONObject ,取出来的对象是LIST,也就是JSONArray ,再把这个JSONArray里面的对象遍历取出来。 json2list()这个方法,是three()这个方法中解析JSONArray 这部份。建议写一上方法,传一个JSONArray 对象进去,返回一个list对象。在看代码前,请先把两个JSON字符串输出看一下,了解结构。