1、提供json響應的是哪種伺服器,web伺服器?應用伺服器?
web json只是數據流
2、如何使用JSON格式 POST數據到伺服器
1. JSON的數據格式
a) 按照最簡單的形式,可以用下面這樣的 JSON 表示名稱/值對:
{ "firstName": "Brett" }
b) 可以創建包含多個名稱/值對的記錄,比如:
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "[email protected]" }
c) 可以創建值的數組
{ "people": [
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "[email protected]" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "[email protected]" }
]}
d) 當然,可以使用相同的語法表示多個值(每個值包含多個記錄):
{ "programmers": [
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "[email protected]" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "[email protected]" }
],
"authors": [
{ "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
{ "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" }
],
"musicians": [
{ "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" }
]
}
注意,在不同的主條目(programmers、authors 和 musicians)之間,記錄中實際的名稱/值對可以不一樣。JSON 是完全動態的,允許在 JSON 結構的中間改變表示數據的方式。
2. 在 JavaScript 中使用 JSON
JSON 是 JavaScript 原生格式,這意味著在 JavaScript 中處理 JSON 數據不需要任何特殊的 API 或工具包。
2.1 將 JSON 數據賦值給變數
例如,可以創建一個新的 JavaScript 變數,然後將 JSON 格式的數據字元串直接賦值給它:
var people =
{ "programmers": [
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "[email protected]" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "[email protected]" }
],
"authors": [
{ "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
{ "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" }
],
"musicians": [
{ "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" }
]
}
2.2 訪問數據
將這個數組放進 JavaScript 變數之後,就可以很輕松地訪問它。實際上,只需用點號表示法來表示數組元素。所以,要想訪問 programmers 列表的第一個條目的姓氏,只需在JavaScript 中使用下面這樣的代碼:
people.programmers[0].lastName;
注意,數組索引是從零開始的。
2.3 修改 JSON 數據
正如訪問數據,可以按照同樣的方式修改數據:
people.musicians[1].lastName = "Rachmaninov";
2.4 轉換回字元串
a) 在 JavaScript 中這種轉換也很簡單:
String newJSONtext = people.toJSONString();
b) 可以將任何 JavaScript 對象轉換為 JSON 文本。並非只能處理原來用 JSON 字元串賦值的變數。為了對名為 myObject 的對象進行轉換,只需執行相同形式的命令:
String myObjectInJSON = myObject.toJSONString();
說明:將轉換回的字元串作為Ajax調用的字元串,完成非同步傳輸。
小結:如果要處理大量 JavaScript 對象,那麼 JSON 幾乎肯定是一個好選擇,這樣就可以輕松地將數據轉換為可以在請求中發送給伺服器端程序的格式。
3. 伺服器端的 JSON
3.1 將 JSON 發給伺服器
a) 通過 GET 以名稱/值對發送 JSON
在 JSON 數據中會有空格和各種字元,Web 瀏覽器往往要嘗試對其繼續編譯。要確保這些字元不會在伺服器上(或者在將數據發送給伺服器的過程中)引起混亂,需要在JavaScript的escape()函數中做如下添加:
var url = "organizePeople.php?people=" + escape(people.toJSONString());
request.open("GET", url, true);
request.onreadystatechange = updatePage;
request.send(null);
b) 利用 POST 請求發送 JSON 數據
當決定使用 POST 請求將 JSON 數據發送給伺服器時,並不需要對代碼進行大量更改,如下所示:
var url = "organizePeople.php?timeStamp=" + new Date().getTime();
request.open("POST", url, true);
request.onreadystatechange = updatePage;
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.send(people.toJSONString());
注意:賦值時格式必須是var msg=eval('(' + req.responseText + ')');
3.2 在伺服器上解釋 JSON
a) 處理 JSON 的兩步驟。
針對編寫伺服器端程序所用的語言,找到相應的 JSON 解析器/工具箱/幫助器 API。
使用 JSON 解析器/工具箱/幫助器 API 取得來自客戶機的請求數據並將數據轉變成腳本能理解的東西。
b) 尋找 JSON 解析器
尋找 JSON 解析器或工具箱最好的資源是 JSON 站點。如果使用的是 Java servlet,json.org 上的 org.json 包就是個不錯的選擇。在這種情況下,可以從 JSON Web 站點下載 json.zip 並將其中包含的源文件添加到項目構建目錄。編譯完這些文件後,一切就就緒了。對於所支持的其他語言,同樣可以使用相同的步驟;使用何種語言取決於您對該語言的精通程度,最好使用您所熟悉的語言。
c) 使用 JSON 解析器
一旦獲得了程序可用的資源,剩下的事就是找到合適的方法進行調用。如果在 servlet 中使用的是 org.json 包,則會使用如下代碼:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) { //report an error }
try {
JSONObject jsonObject = new JSONObject(jb.toString());
} catch (ParseException e) {
// crash and burn
throw new IOException("Error parsing JSON request string");
}
// Work with the data using methods like...
// int someInt = jsonObject.getInt("intParamName");
// String someString = jsonObject.getString("stringParamName");
// JSONObject nestedObj = jsonObject.getJSONObject("nestedObjName");
// JSONArray arr = jsonObject.getJSONArray("arrayParamName");
// etc...
}
3、如何POST一個JSON數據到伺服器
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONStringer;
import android.util.Log;
public class JSON{
//========================================================================
/**
* <b><p> retrieveJSONArray(ArrayList<</String[]>> jsonArray)</b></p>
*
* <ul><li>Returns JSON formed Array from the ArrayList provided.</li>
* <li><b>jsonArray</b> will be ArrayList of array.</li>
* <li>the elements provided in array will be arranged in consecutive keys</li>
* <li>ex:<b> [{"key0","1st element of array"},{"key1","2nd element of array"}]</b> </li>
* </ul>
*/
//========================================================================
public static String retrieveJSONArray(ArrayList<String[]> jsonArray){
try{
String[] jsonObject=new String[2];
JSONStringer stringer=new JSONStringer();
stringer.array();
int arrayLength=jsonArray.size();
for(int i=0;i<arrayLength;i++){
jsonObject=jsonArray.get(i);
stringer.object();
for(int j=0;j<jsonObject.length;j++)
stringer.key("key"+j).value(jsonObject[j]);
stringer.endObject();
}
stringer.endArray();
return stringer.toString();
}catch(Exception e){
e.printStackTrace();
}
return null;
}
//========================================================================
/**
* <b><p> retrieveJSONArray(ArrayList<</String[]>> jsonArray,String[] key)</b></p>
*
* <ul><li>Returns JSON formed Array from the ArrayList provided.</li>
* <li><b>jsonArray</b> will be ArrayList of array.</li>
* <li>the elements provided in array will be arranged in consecutive keys</li>
* <li>ex:<b> [{"key[0]","1st element of array"},{"key[1]","2nd element of array"}]</b> </li>
* </ul>
*/
//========================================================================
public static String retrieveJSONArray(ArrayList<String[]> jsonArray,String[] key){
try{
String[] jsonObject=new String[2];
JSONStringer stringer=new JSONStringer();
stringer.array();
int arrayLength=jsonArray.size();
for(int i=0;i<arrayLength;i++){
jsonObject=jsonArray.get(i);
stringer.object();
for(int j=0;j<jsonObject.length;j++)
stringer.key(key[j]).value(jsonObject[j]);
stringer.endObject();
}
stringer.endArray();
return stringer.toString();
}catch(Exception e){
e.printStackTrace();
}
return null;
}
//========================================================================
/**
* <b><p> retrieveJSONString(ArrayList<</String[]>> jsonArray)</b></p>
*
* <ul><li>Returns JSON formed string from the ArrayList provided.</li>
* <li><b>jsonArray</b> will be ArrayList of array.</li>
* <li>ex:<b> {"key0":"1st element of array","key1":"2nd element of array"}</b> </li>
* </ul>
*/
//========================================================================
public static String retrieveJSONString(ArrayList<String[]> jsonObject){
try{
String[] arr_jsonObject=new String[2];
JSONStringer stringer=new JSONStringer();
stringer.object();
for(int i=0;i<jsonObject.size();i++){
arr_jsonObject=jsonObject.get(i);
stringer.key(arr_jsonObject[0]).value(arr_jsonObject[1]);
}
stringer.endObject();
return stringer.toString();
}catch(Exception e){
e.printStackTrace();
}
return null;
}
//========================================================================
/**
* <p>Converts jsonArray to an arrayList of String[]. Where each row contains values in json
* String array, in increasing order of key values provided, without there key counterparts.
*
* For ex: if JSON string is [{"key00":"value00","key01":"value01"},{"key10":"value10","key11":"value11"}],
* then the rows of an array will be as follows
* <ul><li>First row : 1st element- value00, 2nd element - value01</li>
* <li>Second row : 1st element- value10, 2nd element - value11</li></ul>
* </p>
*
* */
//========================================================================
public static ArrayList<String[]> convertJSONArraytoArrayList(String jsonArray,String[] key){
try{
JSONArray JsonArray=new JSONArray(jsonArray);
JSONObject JsonObject=new JSONObject();
int jsonArraySize=JsonArray.length();
String[] jsonObjectArray;
ArrayList<String[]> jsonArrayList=new ArrayList<String[]>();
for(int i=0;i<jsonArraySize;i++){
JsonObject=JsonArray.getJSONObject(i);
jsonObjectArray=new String[key.length];
for(int j=0;j<key.length;j++)
jsonObjectArray[j]=JsonObject.getString(key[j]);
jsonArrayList.add(jsonObjectArray);
}
return jsonArrayList;
}catch(Exception e){
e.printStackTrace();
return null;
}
}
//========================================================================
/**
* <p>Converts jsonString to an arrayList of String[].
*
* For ex: if JSON string is {"key00":"value00","key01":"value01"},
* then the rows of an array will be as follows
* <ul><li>First row : 1st element- value00</li>
* <li>Second row : 1st element- value10</li></ul>
* </p>
*
* */
//========================================================================
public static ArrayList<String[]> convertJSONStringtoArrayList(String jsonString,String[] key){
try{
JSONObject jsonObject=new JSONObject(jsonString);
ArrayList<String[]> jsonArrayList=new ArrayList<String[]>();
for(int i=0;i<key.length;i++)
jsonArrayList.add(new String[]{jsonObject.getString(key[i])});
return jsonArrayList;
}catch(Exception e){
e.printStackTrace();
return null;
}
}
}
4、json數據上傳到伺服器的方式有哪些
如果圖片已經在伺服器上,你把圖片在伺服器的相對路徑字元串作為JSON的屬性傳過去,不是就能顯示了?
如果圖片是需要上傳的,瀏覽器的window有個FileReader對象,調用filereader.readAsDataURL()這個方法能轉換成實際要傳的數據,格式就是JSON的。
5、如何向伺服器發送json數據
版權聲明:本文為博主原創文章,未經博主允許不得轉載。
Ajax中可以使用xml作為參數發送給伺服器,除了XML還可以使用JSON(http://www.json.org/json-zh.html)
XML的一個替代方法是JSON,JSON是一種文本格式,它獨立於具體語言,JSON建立在以下兩種數據結構基礎上:
名/值對集合,在不同的語言中,被實現為一個對象、記錄、結構或字典
值的有序表,在大部分語言中,實現為數組
JSON可以做為異構系統之間的一種數據互換格式。
JSON對象是名/值對的無序集合({},使用「:」分隔),JSON數組是一個有序的值集合([],使用「,」分隔)
如下就是一個JSON格式的數據:
var employee = {
「firstName」 : John
, 「lastName」 : Do
6、伺服器如返回JSON
jQuery ajax請求
按照json格式拼接好字元串返回就行了
返回
伺服器端代碼
PrintWriter writer = response.getWriter();
writer.write(jo.toString()); //這里是你要返回的字元串
writer.flush();
writer.close();
//url是請求的伺服器地址
//data是請求的參數,格式data:{id:1,name:'user1'}
jQuery.ajax({type:"POST", url:"member_overtime.action",data:{}, beforeSend:function () {
//提交數據狀態
}, success:function (data) {
//伺服器端返回參數處理
var objJson = eval("(" + data + ")"); //json字元串轉換為Object
//通過ojbJson.key 操作 類似與map
}});
7、簡述讀取網站伺服器上json的步驟
json數組用js解析並顯示的方法:
假如後台返回的數據是:
{'id':1,'name':'st','grant':[{'tm_id':1,'tm_name':'zc'},{'tm_id':2,'tm_name':'ww'}]}
前台獲取:
var data = eval_r("(" + json + ")");//json為接收的後台返回的數據;
var id1 = data.grant[0].tm_id;
var name1 = data.grant[0].tm_name;
var id2 = data.grant[1].tm_id;
var name2 = data.grant[1].tm_name;
循環讀取:
for(var i=0;i<data.grant.length;i++){
alert(data.grant[i].tm_id+"---"+data.grant[i].tm_name);
}
在對應表格中顯示即可。
8、如何上傳json格式的數據到伺服器?
首先,你可以手動拼json。然後是人ajax的方式,或者window.loacation=url的方式向服務端提交。
其次,但是不管你怎麼拼,都不能發送圖片等文件到伺服器!
這並不是說json格式不行,而是在頁面上發送信息到服務端的時候文件類的是由瀏覽器自動轉為流的,而你在頁面上的任何腳本都不能讀取文件!
9、怎麼解析從伺服器返回的json
json數據格式解析我自己分為兩種;
一種是普通的,一種是帶有數組形式的;
普通形式的:
伺服器端返回的json數據格式如下:
復制代碼代碼如下:
{"userbean":{"Uid":"100196","Showname":"\u75af\u72c2\u7684\u7334\u5b50","Avtar":null,"State":1}}
分析代碼如下:
復制代碼代碼如下:
// TODO 狀態處理 500 200
int res = 0;
res = httpClient.execute(httpPost).getStatusLine().getStatusCode();
if (res == 200) {
/*
* 當返回碼為200時,做處理
* 得到伺服器端返回json數據,並做處理
* */
HttpResponse httpResponse = httpClient.execute(httpPost);
StringBuilder builder = new StringBuilder();
BufferedReader bufferedReader2 = new BufferedReader(
new InputStreamReader(httpResponse.getEntity().getContent()));
String str2 = "";
for (String s = bufferedReader2.readLine(); s != null; s = bufferedReader2
.readLine()) {
builder.append(s);
}
Log.i("cat", ">>>>>>" + builder.toString());
JSONObject jsonObject = new JSONObject(builder.toString())
.getJSONObject("userbean");
String Uid;
String Showname;
String Avtar;
String State;
Uid = jsonObject.getString("Uid");
Showname = jsonObject.getString("Showname");
Avtar = jsonObject.getString("Avtar");
State = jsonObject.getString("State");
帶數組形式的:
伺服器端返回的數據格式為:
復制代碼代碼如下:
{"calendar":
{"calendarlist":
[
{"calendar_id":"1705","title":"(\u4eb2\u5b50)ddssd","category_name":"\u9ed8\u8ba4\u5206\u7c7b","showtime":"1288927800","endshowtime":"1288931400","allDay":false},
{"calendar_id":"1706","title":"(\u65c5\u884c)","category_name":"\u9ed8\u8ba4\u5206\u7c7b","showtime":"1288933200","endshowtime":"1288936800","allDay":false}
]
}
}
分析代碼如下:
復制代碼代碼如下:
// TODO 狀態處理 500 200
int res = 0;
res = httpClient.execute(httpPost).getStatusLine().getStatusCode();
if (res == 200) {
/*
* 當返回碼為200時,做處理
* 得到伺服器端返回json數據,並做處理
* */
HttpResponse httpResponse = httpClient.execute(httpPost);
StringBuilder builder = new StringBuilder();
BufferedReader bufferedReader2 = new BufferedReader(
new InputStreamReader(httpResponse.getEntity().getContent()));
String str2 = "";
for (String s = bufferedReader2.readLine(); s != null; s = bufferedReader2
.readLine()) {
builder.append(s);
}
Log.i("cat", ">>>>>>" + builder.toString());
/**
* 這里需要分析伺服器回傳的json格式數據,
*/
JSONObject jsonObject = new JSONObject(builder.toString())
.getJSONObject("calendar");
JSONArray jsonArray = jsonObject.getJSONArray("calendarlist");
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject2 = (JSONObject)jsonArray.opt(i);
CalendarInfo calendarInfo = new CalendarInfo();
calendarInfo.setCalendar_id(jsonObject2.getString("calendar_id"));
calendarInfo.setTitle(jsonObject2.getString("title"));
calendarInfo.setCategory_name(jsonObject2.getString("category_name"));
calendarInfo.setShowtime(jsonObject2.getString("showtime"));
calendarInfo.setEndtime(jsonObject2.getString("endshowtime"));
calendarInfo.setAllDay(jsonObject2.getBoolean("allDay"));
calendarInfos.add(calendarInfo);
}
總結,普通形式的只需用JSONObject ,帶數組形式的需要使用JSONArray 將其變成一個list。
10、json 通過ip地址傳數據到伺服器
json只是一個字元串數據格式而已,我沒記錯的話格式好像是鍵值對的(我幾年沒看了),{鍵:值;鍵:值},不記得是不是這樣,你既然說了用JS,那你應該是在做網頁吧。如果不想刷新頁面,用Ajax就可以了。或者你直接用Post表單的形式傳送也可以,只要你伺服器端能收到數據就行了。JSON就是一個字元串。傳輸到伺服器你自己處理就可以了。我還從來沒用JSON,w3cSchool的教程就像說明書,很簡陋,自己找本好書看吧