package com.longtop.ajax.json;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class TestServlet {
public static void main(String[] args){
TestServlet ts=new TestServlet();
System.out.println(ts.dellJson());
//JSONObjectjo=JSONObject.fromObject(ts.dellJson());
try{
JSONObjectjo=newJSONObject(ts.dellJson());
JSONArray asonArray = jo.getJSONArray("addressbood");
Object o = asonArray.get(1);
JSONObjectjo1 = (JSONObject)o;
System.out.println(jo1.toString());
//JSONArray array=jo1.getJSONArray("address");
System.out.println(jo1.get("address"));
JSONArray asonArray1 = jo1.getJSONArray("address");
JSONObjectjo11 = (JSONObject)asonArray1.get(0);
System.out.println(jo11.getString("city"));
}catch(JSONException a){
a.printStackTrace();
}
}
public String dellJson(){
String str="";
Map map=new HashMap();
Address maryLebow = new Address("5 Main Street","San Diego,CA","91912","619-332-3452","664-223-4667");
map.put("Mary Lebow",maryLebow);
Address amySmith = new Address("25 H Street","Los Angeles,"95212","660-332-3452","541-223-4667");
map.put("Sally May",amySmith);
Address johnKim = new Address("2343 Sugarland Drive","Houston,TX","55212","554-332-3412","461-223-4667");
map.put("John Kim",johnKim);
Address richardThorn = new Address("14 68th Street","New York,NY","12452","212-132-6182","161-923-4001");
map.put("Richard Thorn",richardThorn);
Iterator it=map.entrySet().iterator();
JSONArray ja=new JSONArray();
while(it.hasNext()){
Map.Entry e=(Map.Entry)it.next();
String name=(String)e.getKey();
Address add=(Address)e.getValue();
String city=add.getCity();
String street=add.getStreet();
String zip=add.getZip();
String phone1=add.getPhoneNumber1();
String phone2=add.getPhoneNumber2();
try{
JSONObjectjbAddress=newJSONObject();
jbAddress.append("street",street);
jbAddress.append("city",city);
jbAddress.append("zip",zip);
JSONArray jaPhone=new JSONArray();
jaPhone.put( phone1);
jaPhone.put( phone2);
JSONObjectjbAddressBook=newJSONObject();
jbAddressBook.append("name",name);
jbAddressBook.append("address",jbAddress);
jbAddressBook.append("phoneNumbers",jaPhone);
ja.put(jbAddressBook);
}catch(JSONException a){
a.printStackTrace();
}
}
try{
str=newJSONObject().put("addressbood",ja).toString(); }catch(JSONException a){ a.printStackTrace(); } return str; } }