JSON伺服器的使用和客戶端的解析
阿新 • • 發佈:2019-01-10
伺服器端的使用:
String jsonString="";
String action_flag=request.getParameter("action_flag");
if(action_flag=request.getParameter("action_flag"));
{
jsonString=JsonTools.createJsonString("person",service.getPersin);
//通過使用JsonTools工具類把資料封裝成String串
}
客戶端Json資料的解析
寫一個HttpUtils工具類
public static String getJsonContent (String url_path){
try{
URL url=new URL(url_path);
HttpURLConnection connection=(HttpURlConnection)
url.openConnection();
connection.setConnectTimeout(3000);
connection.setRequestMethod("GET");
connection.setDoInput(true);
int code=connection.getResponseCode();
if(code==200){
return changeInputStream(InputStream inputStream);;
}
}
}
public static String changeInputStream(InputStream inputStream){
String jsonString="";
ByteArrayOutPutStream outputStream=new ByteArrayoutPutStream();
int len=0;
byte[] data=new byte[1024];
try{
while((len=InputStream.read(data))!=0){
outputStream.write(data,0,len);
}
jsonString=new String(outputStream.toByteArray());
}
}
通過使用JsonObject類或者是JsonArray來解析Json字串
public class JsonTools{
public static Person getPerson(String key,String jsonString){
try{
JSONObject jsonObject=new JSONObject(jsonString);
JSONObject personObject=jsonObject.getJSONObject("person");
person.setname(personObject.getString("name"));
}
}
}