⑴ 怎麼跨域獲取到json數據呢伺服器端有什麼要求嗎
1、通過jQuery的ajax進行跨域,這其實是採用的jsonp的方式來實現的。
jsonp是英文json with padding的縮寫。它允許在伺服器端生成script tags至返回至客戶端,也就是動態生成javascript標簽,通過javascript callback的形式實現數據讀取。
html頁面端示例代碼:
復制代碼 代碼如下:
//首先要引入jquery的js包
jQuery(document).ready(function(){
$.ajax({
type : "get", //jquey是不支持post方式跨域的
async:false,
url : "http://api.taobao.com/apitools/ajax_props.do", //跨域請求的URL
dataType : "jsonp",
//傳遞給請求處理程序,用以獲得jsonp回調函數名的參數名(默認為:callback)
jsonp: "jsoncallback",
//自定義的jsonp回調函數名稱,默認為jQuery自動生成的隨機函數名
jsonpCallback:"success_jsonpCallback",
//成功獲取跨域伺服器上的json數據後,會動態執行這個callback函數
success : function(json){
alert(json);
}
});
});
⑵ 用java寫伺服器怎麼獲得從前端傳來的json數據
通過 JSONObject類就可以了
首先 你把這幾個包 下下來 放到你項目。如果有就不要下了:
1.commons-lang.jar
2.commons-beanutils.jar
3.commons-collections.jar
4.commons-logging.jar
5.ezmorph.jar
6.json-lib-2.2.2-jdk15.jar
像你這種是數據形式 就通過 JSONArray 如:
JSONArray datasJson = JSONArray.fromObject(datas);最好把datas toString 一下
⑶ webservice介面已經知道,android怎樣獲取伺服器中的json數據,怎樣在客戶端顯示出來
看你那邊什麼webservice介面,不一樣的介面,請求方式不一樣,但是多數是http請求介面,請求回來的數據,通過解析json格式,顯示到你要顯示的控制項就可以了。
⑷ 如何用Retrofit直接獲得Json數據
直接上個實例吧。
通過retrofit庫post一串json格式的數據。首先post的json數據格式如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
{
"Id": "string",
"DeviceId": "string",
"Name": "string",
"SumDistance": 0,
"RouteNo": "string",
"SumPoints": 0,
"SetupTime": "2016-06-10T13:11:00.766Z",
"UsedTime": 0,
"Points": [
{
"Id": "string",
"RouteNo": "string",
"Name": "string",
"Longitude": "string",
"Latitude": "string",
"Height": 0,
"Distance": 0,
"Yaw": 0,
"Pitch": 0,
"Speed": 0,
"Usedtime": 0
}
]
}
通過安裝Android studio gsonformat插件,根據上面的json格式自動生成一個Bean類,本文命名為FlyRouteBean,
1
2
3
4
5
6
7
然後就來建立介面了,其內容如下:
[java] view plain
public interface PostRoute {
@Headers({"Content-Type: application/json","Accept: application/json"})//需要添加頭
@POST("api/FlyRoute/Add")
Call<FlyRouteBean> postFlyRoute(@Body RequestBody route);//傳入的參數為RequestBody
}
接下來就是提交數據的了:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
FlyRouteBean flyRouteBean=new FlyRouteBean();
flyRouteBean=initdata(flyRouteBean);//根據Bean類初始化一個需要提交的數據類
Gson gson=new Gson();
String route= gson.toJson(flyRouteBean);//通過Gson將Bean轉化為Json字元串形式
[java] view plain
Retrofit retrofit=new Retrofit.Builder()
.baseUrl(URL)
.addConverterFactory( GsonConverterFactory.create())
.build();
PostRoute postRoute=retrofit.create(PostRoute.class);
RequestBody body=RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),route);
Call<FlyRouteBean> call=postRoute.postFlyRoute(body);
call.enqueue(new Callback<FlyRouteBean>() {
@Override
public void onResponse(Call<FlyRouteBean> call, Response<FlyRouteBean> response) {
Log.e("sssss","-----------------------"+response.body().getDeviceId());//這里是用於測試,伺服器返回的數據就是提交的數據。
}
@Override
public void onFailure(Call<FlyRouteBean> call, Throwable t) {
Log.e("sssss",t.getMessage());
}
});
⑸ 已知JSON字元串,如何在本地模擬伺服器返回JSON,用火狐工具分析結構
尊敬的用戶,您好!很高興為您答疑。
其實不管數據格式是什麼類型,您都可以在本地直接新建一個包含json數據的txt文件,然後直接讀取該文件的路徑(據對路徑即可)。如果本地假設有伺服器,放在伺服器的webroot下進行本地訪問效果更好。以上2種方式都可以實現模擬數據。
希望我的回答對您有所幫助,如有疑問,歡迎繼續咨詢我們。
⑹ 如何讀取Json文件的數據
json文件是一種輕量級的數據交互格式。一般在jquery中使用getJSON()方法讀取。
$.getJSON(url,[data],[callback])
url:載入的頁面地址
data: 可選項,發送到伺服器的數據,格式是key/value
callback:可選項,載入成功後執行的回調函數
1.首先建一個JSON格式的文件userinfo.json 保存用戶信息。如下:
?
1234567891011121314151617
[{"name":"張國立","sex":"男","email":"[email protected]"},{"name":"張鐵林","sex":"男","email":"[email protected]"},{"name":"鄧婕","sex":"女","email":"[email protected]"}]
2.其次建一個頁面用於獲取JSON文件里的用戶信息數據,並顯示
?
04142
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>getJSON獲取數據</title><script type="text/javascript" src="js/jquery-1.8.2.min.js"></script><style type="text/css">#divframe{ border:1px solid #999; width:500px; margin:0 auto;}.loadTitle{ background:#CCC; height:30px;}</style>< script type = "text/javascript" >$(function (){ $("#btn").click(function () { $.getJSON("js/userinfo.json", function (data){ var $jsontip = $("#jsonTip"); var strHtml = "123"; //存儲數據的變數 $jsontip.empty(); //清空內容 $.each(data, function (infoIndex, info){ strHtml += "姓名:" + info["name"] + "<br>"; strHtml += "性別:" + info["sex"] + "<br>"; strHtml += "郵箱:" + info["email"] + "<br>"; strHtml += "<hr>" }) $jsontip.html(strHtml); //顯示處理後的數據 }) })})</script></head><body><div id="divframe"><div class="loadTitle"><input type="button" value="獲取數據" id="btn"/></div><div id="jsonTip"></div></div></body></html>
⑺ 如何解析伺服器返回的json數據
//這種要用post方式了,//將json數據以字元串的方式上傳給伺服器,//當然你要確保json格式的
⑻ 怎麼解析從伺服器返回的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。
⑼ android 在伺服器端生成json格式數據,在客戶端怎麼解析
因為這次要從伺服器端得到Json數據,並且通過解析之後把解析後的數據顯示在Android客戶端中,首先部署伺服器端代碼(直接使用Jsp/Servlet):
構造的Json數據如下:
[{"name":"張三","address":"北京","age":20},{"name":"李四","address":"上海","age":30},{"name":"王五","address":"深圳","age":35}]
[一]伺服器端(Person.java省略):
①:數據構造JsonService.java
public class JsonService {
public static List<Person> getListPerson() {
List<Person> mLists = new ArrayList<Person>();
mLists.add(new Person("張三", "北京", 20));
mLists.add(new Person("李四", "上海", 30));
mLists.add(new Person("王五", "深圳", 35));
return mLists;
}
②:Servlet的代碼(包括構造Json數據,沒有使用Json數據轉換方法)JsonServlet.java
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
List<Person> persons = JsonService.getListPerson();
StringBuffer sb = new StringBuffer();
sb.append('[');
for (Person person : persons) {
sb.append('{').append("\"name\":").append("\""+person.getName()+"\"").append(","); sb.append("\"address\":").append("\""+person.getAddress()+"\"").append(",");
sb.append("\"age\":").append(person.getAge());
sb.append('}').append(",");
}
sb.deleteCharAt(sb.length() - 1);
sb.append(']');
out.write(new String(sb));
out.flush();
out.close();
}
③:部署到Tomact 瀏覽器輸入http://localhost/JsonWeb/JsonServlet直接訪問結果如下:
[{"name":"張三","address":"北京","age":20},{"name":"李四","address":"上海","age":30},{"name":"王五","address":"深圳","age":35}]
至此伺服器端代碼編碼完成,下面進行客戶端代碼編寫; (二)客戶端(Person類,和展示數據的布局文件因為簡單省去) ①:獲取伺服器端的Json數據並且解析的工具類JsonParse.java 必要的需要導入的包省去
public class JsonParse {
/**
* 解析Json數據
*
* @param urlPath
* @return mlists
* @throws Exception
*/
public static List<Person> getListPerson(String urlPath) throws Exception {
List<Person> mlists = new ArrayList<Person>();
byte[] data = readParse(urlPath);
JSONArray array = new JSONArray(new String(data));
for (int i = 0; i < array.length(); i++) {
JSONObject item = array.getJSONObject(i);
String name = item.getString("name");
String address = item.getString("address");
int age = item.getInt("age");
mlists.add(new Person(name, address, age));
}
return mlists;
}
/**
* 從指定的url中獲取位元組數組
*
* @param urlPath
* @return 位元組數組
* @throws Exception
*/
public static byte[] readParse(String urlPath) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int len = 0;
URL url = new URL(urlPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream inStream = conn.getInputStream();
while ((len = inStream.read(data)) != -1) {
outStream.write(data, 0, len);
}
inStream.close();
return outStream.toByteArray();
}
}
②:主Activity類
public class MainActivity extends Activity {
private Button mButton;
private ListView mListView;
//使用IP不能使用localhost或者127.0.0.1,因為android模擬器默認綁定這個IP,這里應該訪問區域網IP
private static final String urlPath = "http://10.16.31.207/JsonWeb/JsonServlet";
private static final String TAG = "MainActivity";
private List<Person> persons;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mButton = (Button) findViewById(R.id.button1);
mListView = (ListView) findViewById(R.id.listView1);
mButton.setOnClickListener(new MyOnClickListener());
}
private class MyOnClickListener implements OnClickListener {
@Override
public void onClick(View v) {
try {
// 得到Json解析成功之後數據
persons = JsonParse.getListPerson(urlPath);
List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
for (int i = 0; i < persons.size(); i++) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("name", persons.get(i).getName());
map.put("address", persons.get(i).getAddress());
map.put("age", persons.get(i).getAge());
data.add(map);
}
//初始化適配器,並且綁定數據
SimpleAdapter _Adapter = new SimpleAdapter(MainActivity.this,
data, R.layout.listview_item, new String[] { "name",
"address", "age" }, new int[] { R.id.textView1,
R.id.textView2, R.id.textView3 });
mListView.setAdapter(_Adapter);
} catch (Exception e) {
Toast.makeText(MainActivity.this, "解析失敗", 2000).show();
Log.i(TAG, e.toString());
}
}
}