package sina.jsontest.test;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class NetWorkOperator {
/**
* @reference
* 1.<a href="http://www.cnblogs.com/MyFavorite/archive/2010/10/19/1855758.html">http://www.cnblogs.com/MyFavorite/archive/2010/10/19/1855758.html</a><br>
* 2.<a href="http://www.blogjava.net/pengpenglin/archive/2008/12/16/220350.html">http://www.blogjava.net/pengpenglin/archive/2008/12/16/220350.html</a><br>
* @param args
* @throws Exception
*/
public static void main(String[] args)throws Exception {
NetWorkOperator kx=new NetWorkOperator();
String json=kx.getReponse(SinaJsonTest.SinaUrl);
kx.JSONNodeParse(json);
}
/**
* <b>获取指定的URL返回的数据信息</b>
* @param <font color="#efac10"><a href="http://www.baidu.com">_url:指定的URL</a></font>
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public String getReponse(String _url) throws ClientProtocolException, IOException
{
String readContent=null;
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(SinaJsonTest.SinaUrl);
System.out.println("0.Send the URL to Sina Sever....");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("1.Get Response Status: " + response.getStatusLine());
if (entity != null) {
System.out.println(" Get ResponseContentEncoding():"+entity.getContentEncoding());
System.out.println(" Content Length():"+entity.getContentLength());
//getResponse
InputStream in=entity.getContent();
int count = 0;
while (count == 0) {
count = Integer.parseInt(""+entity.getContentLength());//in.available();
}
byte[] bytes = new byte[count];
int readCount = 0; // 已经成功读取的字节的个数
while (readCount <= count) {
if(readCount == count)break;
readCount += in.read(bytes, readCount, count - readCount);
}
//转换成字符串
readContent= new String(bytes, 0, readCount, "UTF-8"); // convert to string using bytes
System.out.println("2.Get Response Content():\n"+readContent);
}
return readContent;
}
/**
* @core 重点用到了readTree方法:
* 1.从文件读取
* ObjectMapper mapper = new ObjectMapper();
* JsonFactory f = new JsonFactory();
* JsonParser jp = f.createJsonParser(new File(fileName));
* JsonNode root = mapper.readTree(jp);
* 2.从字符串读取
* ObjectMapper mapper = new ObjectMapper();
* JsonNode userRootNode = mapper.readTree(json);
* <br/><font color='red'>Java JSON</font>
* @param <cite>fileName</cite>=<b>FilePath+FileName</b>
*/
public void JSONNodeParse(String json) {
try {
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(json);
System.out.println("Source:\n"+root.toString());
JsonNode userInfoNode = root.path("users").get(0);
System.out.println("userInfo:" + userInfoNode.toString());// 还可以继续解析
int next_cursor = root.path("next_cursor").getIntValue();
System.out.println("next_cursor:" + next_cursor);
JsonNode previous_cursorNode = root.path("previous_cursor");
System.out.println("previous_cursorNode:"
+ previous_cursorNode.getIntValue());
for (JsonNode node : root.path("users")) {
System.out.println("Full Entry: " + node.toString());
// 解析userInfoNode
String sub_json = node.toString();
try {
JsonNode userRootNode = mapper.readTree(sub_json);
System.out.println("UserRoot Node Size:"+ userRootNode.size());
Iterator<String> itr = null;
for (JsonNode _node : userRootNode) {
itr=_node.getFieldNames();
//System.out.println("Entry(followers_count): "
// + _node.path("followers_count").getValueAsText());
while (itr.hasNext()) {
String fieldName = itr.next();
if(fieldName.equals("province"))
System.out.println("province exists!");
if (_node.path(fieldName).toString().startsWith("\"")
&& _node.path(fieldName).toString().endsWith("\""))
System.out.println("Entry("+ fieldName+ "): "
+ _node.path(fieldName).toString().substring(
1,_node.path(fieldName).toString().length() - 1));
else
System.out.println("Entry(" + fieldName + "): "
+ _node.path(fieldName).toString());
}
}
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
用到的 *.jar 包如下:
Eclipse测试通过!分享出来供大家参考。