json解析类

package test;

import java.util.List;

 

import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
//import org.json.JSONObject;

 

 


public class ExampleTest {
private static void post(JSONObject jsonObject) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.baidu.com");
JSONObject response = null;
try {
post.setEntity(new StringEntity(jsonObject.toString(),"UTF-8"));
HttpResponse res = client.execute(post);
System.out.println("状态码:"+res.getStatusLine().getStatusCode());
if(res.getStatusLine().getStatusCode()==200){
HttpEntity entity = res.getEntity();
String content = EntityUtils.toString(entity, "UTF-8");
response=JSONObject.fromObject(content);
System.out.println("Respone Msg:" + response);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("deprecation")
public static void main(String[] args) {
JSONObject jsonObject = new JSONObject();


post(jsonObject);


//json解析数组.
// String sJson = "[{'gwcxxid':'1','spsl':'2'},{'gwcxxid':'1','spsl':'2'},{'gwcxxid':'3','spsl':'4'}]";
// JSONArray jsonArray = new JSONArray(sJson);
// int iSize = jsonArray.length();
// System.out.println("Size:" + iSize);
// for (int i = 0; i < iSize; i++) {
// JSONObject jsonObj = jsonArray.getJSONObject(i);
// System.out.println("[" + i + "]gwcxxid=" + jsonObj.get("gwcxxid"));
// System.out.println("[" + i + "]spsl=" + jsonObj.get("spsl"));
// System.out.println();
// }
// JSONArray ja=new JSONArray(sJson);
// for(int i=0;i<ja.length();i++){
// JSONObject jsonObject = ja.getJSONObject(i);
// System.out.println("gwxxid:"+jsonObject.get("gwcxxid")+",spsl:"+jsonObject.get("spsl"));
// }

// String jsonString = "{\"UserName\":\"ZHULI\",\"age\":\"30\",\"workIn\":\"ALI\",\"Array\":[\"ZHULI\",\"30\",\"ALI\"]}";
// net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(jsonString);
// if(jsonObject.has("UserName")){
// System.out.println("username:"+jsonObject.getString("UserName")+",age:"+jsonObject.get("age")+",workIn:"+jsonObject.get("workIn"));
// }
// if(jsonObject.has("Array")){
// net.sf.json.JSONArray jsonArray = jsonObject.getJSONArray("Array");
// for(int i=0;i<jsonArray.size();i++){
// System.out.println(jsonArray.getString(i));
// }
// }
}


}

posted @ 2015-12-31 09:36  java高级技术汇  阅读(151)  评论(0编辑  收藏  举报