导航:首页 > IDC知识 > json服务器

json服务器

发布时间:2020-09-26 20:29:40

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的教程就像说明书,很简陋,自己找本好书看吧

与json服务器相关的知识