當前位置:首頁 » 安卓系統 » androidjsonget請求

androidjsonget請求

發布時間: 2023-05-01 00:15:01

1. Android開發之Json解析是getInt和optInt的區別

getInt 獲取指定的欄位的int值,若欄位不存在拋異常

源代碼:

java">/**
*森攜Returnsthevaluemappedby{@code此虛伏name}ifitexistsandisanintor
*canbecoercedtoanint,orthrowsotherwise.
*
*@'texistorcannotbecoerced
*toanint.
*/
publicintgetInt(Stringname)throwsJSONException{
Objectobject=get(name);
Integerresult=JSON.toInteger(object);
譽早if(result==null){
throwJSON.typeMismatch(name,object,"int");
}
returnresult;
}

optInt 同樣功能,若欄位不存在 得到是0 ,optString 是null;

源代碼:

/**
*Returnsthevaluemappedby{@codename}ifitexistsandisanintor
*canbecoercedtoanint,or0otherwise.
*/
publicintoptInt(Stringname){
returnoptInt(name,0);
}

2. android怎麼讀取外部json文件

比如說讀取sd卡里的
privatestaticStringSDCardPATH=Environment.getExternalStorageDirectory()+"/";

/**
*讀取文本文件
*
*@paramfilePath
*@return
*/
(StringfilePath){
StringBuildersb=newStringBuilder();
try{
Filefile=newFile(SDCardPATH+filePath);
InputStreamin=null;
in=newFileInputStream(file);
inttempbyte;
while((tempbyte=in.read())!=-1){
sb.append((char)tempbyte);
}
in.close();
}catch(Exceptione){
e.printStackTrace();
}
returnsb.toString();
}


然後你就可以進行你的解析json了。

3. android json解析三種方式哪種效率最高

用org.json以及谷歌提供gson來解析json數據的方式更好一些。

安卓下通常採用以下幾種方式解析json數據:
1、org.json包(已經集成到android.jar中了)
2、google提供的gson庫
3、阿里巴巴的fastjson庫
4、json-lib

以Google出品的Gson為例,具體步驟為:
1、首先,從 code.google.com/p/google-gson/downloads/list下載GsonAPI:
google-gson-1.7.1-release.zip 把gson-1.7.jar 到libs(項目根目錄新建一個libs文件夾)中。 可以使用以下兩種方法解析JSON數據,通過獲取JsonReader對象解析JSON數據。
代碼如下:
String jsonData = "[{\"username\":\"arthinking\",\"userId\":001},{\"username\":\"Jason\",\"userId\":002}]";
try{
JsonReader reader = new JsonReader(new StringReader(jsonData));
reader.beginArray();
while(reader.hasNext()){
reader.beginObject();
while(reader.hasNext()){
String tagName = reader.nextName();
if(tagName.equals("username")){
System.out.println(reader.nextString());
}
else if(tagName.equals("userId")){
System.out.println(reader.nextString());
}
}
reader.endObject();
}
reader.endArray();
}
catch(Exception e){
e.printStackTrace();
}
2、使用Gson對象獲取User對象數據進行相應的操作:
代碼如下:

Type listType = new TypeToken<LinkedList<User>>(){}.getType();
Gson gson = new Gson();
LinkedList<User> users = gson.fromJson(jsonData, listType);
for (Iterator iterator = users.iterator(); iterator.hasNext();) {
User user = (User) iterator.next();
System.out.println(user.getUsername());
System.out.println(user.getUserId());
}
3、如果要處理的JSON字元串只包含一個JSON對象,則可以直接使用fromJson獲取一個User對象:
代碼如下:

String jsonData = "{\"username\":\"arthinking\",\"userId\":001}";
Gson gson = new Gson();
User user = gson.fromJson(jsonData, User.class);
System.out.println(user.getUsername());
System.out.println(user.getUserId());

4. Android請求php伺服器的JSON問題

因為PHP會默認添加一個bom頭信息 有幾個位元組 你得去掉 一般是四個位元組
package cn.image.sky.util;

import java.io.*;

/**
* Generic unicode textreader, which will use BOM mark to identify the encoding
* to be used. If BOM is not found then use a given default or system encoding.
*/
public class UnicodeReader extends Reader {
PushbackInputStream internalIn;
InputStreamReader internalIn2 = null;
String defaultEnc;

private static final int BOM_SIZE = 4;

/**
*
* @param in
* inputstream to be read
* @param defaultEnc
* default encoding if stream does not have BOM marker. Give NULL
* to use system-level default.
*/
UnicodeReader(InputStream in, String defaultEnc) {
internalIn = new PushbackInputStream(in, BOM_SIZE);
this.defaultEnc = defaultEnc;
}

public String getDefaultEncoding() {
return defaultEnc;
}

/**
* Get stream encoding or NULL if stream is uninitialized. Call init() or
* read() method to initialize it.
*/
public String getEncoding() {
if (internalIn2 == null)
return null;
return internalIn2.getEncoding();
}

/**
* Read-ahead four bytes and check for BOM marks. Extra bytes are unread
* back to the stream, only BOM bytes are skipped.
*/
protected void init() throws IOException {
if (internalIn2 != null)
return;

String encoding;
byte bom[] = new byte[BOM_SIZE];
int n, unread;
n = internalIn.read(bom, 0, bom.length);

if ((bom[0] == (byte) 0x00) && (bom[1] == (byte) 0x00)
&& (bom[2] == (byte) 0xFE) && (bom[3] == (byte) 0xFF)) {
encoding = "UTF-32BE";
unread = n - 4;
} else if ((bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE)
&& (bom[2] == (byte) 0x00) && (bom[3] == (byte) 0x00)) {
encoding = "UTF-32LE";
unread = n - 4;
} else if ((bom[0] == (byte) 0xEF) && (bom[1] == (byte) 0xBB)
&& (bom[2] == (byte) 0xBF)) {
encoding = "UTF-8";
unread = n - 3;
} else if ((bom[0] == (byte) 0xFE) && (bom[1] == (byte) 0xFF)) {
encoding = "UTF-16BE";
unread = n - 2;
} else if ((bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE)) {
encoding = "UTF-16LE";
unread = n - 2;
} else {
// Unicode BOM mark not found, unread all bytes
encoding = defaultEnc;
unread = n;
}
// System.out.println("read=" + n + ", unread=" + unread);

if (unread > 0)
internalIn.unread(bom, (n - unread), unread);

// Use given encoding
if (encoding == null) {
internalIn2 = new InputStreamReader(internalIn);
} else {
internalIn2 = new InputStreamReader(internalIn, encoding);
}
}

public void close() throws IOException {
init();
internalIn2.close();
}

public int read(char[] cbuf, int off, int len) throws IOException {
init();
return internalIn2.read(cbuf, off, len);
}

}

這個類 你看看 可以解決你的問題

5. java怎麼接收android請求過來的json數據

java接收android請求json數據的方法:

  • 如果發送的沒有參數名稱你可以直接得到請求體,如
    InputStreaminputStream=urlConnection.getInputStream();
    Stringencoding=urlConnection.getContentEncoding();
    Stringbody=IOUtils.toString(inputStream,encoding);
    System.out.println(body);

  • 如果body就是那個json內容使用fastjson進行解析就可以了
    JSONObjectmap=JSON.parseObject(body);
    System.out.println(map.getString("mobileNo"));//還是System.out.println(map.get("mobileNo"));?具體看一下介面文檔

  • 或者
    Mapmap=JSON.parseObject(body,Map.class);
    System.out.println(map.get("mobileNo"));

6. android 怎麼用json解析介面(本人新手,請大手幫忙解決下)

fastjson.jar這個jar包可以方便的幫你解析json格式數據:
你可以參考下我這段代碼:
public Object parseMap_Sub(String str) {
try {

Map<String, Object> map = JSON.parseObject(str);
JSONArray jsonArray = (JSONArray) map.get("data");
List<NearMap_Info> list_detial = new ArrayList<NearMap_Info>();
for (Object o : jsonArray) {
Map<String, String> map_1 = (Map<String, String>) o;
NearMap_Info audio_info = new NearMap_Info();
//audio_info.setSize((String) map.get("size"));
audio_info.setFlag(map_1.get("flag"));
audio_info.setTitle(map_1.get("title"));
audio_info.setUrl(map_1.get("url"));
audio_info.setType(map_1.get("type"));
audio_info.setId(map_1.get("id"));
audio_info.setImg(map_1.get("img"));
list_detial.add(audio_info);
}
ro.result = true;
ro.obj = list_detial;
} catch (Exception e) {
e.printStackTrace();
ro.result = false;
}
return ro;
}

7. Android studio使用Retrofit框架,Get發送請求,Gson解析返回的json數據時報錯怎麼辦

資料庫一直以來給我的感覺就是——麻煩!!!
接觸了Realm之後才終於可以開開心心的使用資料庫了。
本文總結一些Realm資料庫的常用知識點,包括多線程訪問,以及如何與Retrofit2.0一起使用等...
看懂這些知識點之後,個人認為就可以在一般的項目中使用Realm了。

1. model類必須extends RealmObject,所有屬性必須用private修飾

2. model中支持基本數據結構:boolean, byte, short, ìnt, long, float, double, String, Dateand byte[]

3.若要使用List必須用RealmList<T>,或者繼承RealmList

4.與Retrofit2.*一起使用,通過Gson來解析Json數據並直接生成RealmObject,可參考如下寫法:

[java] view plain
Gson gson = new GsonBuilder()
.setExclusionStrategies(new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes f) {
return f.getDeclaringClass().equals(RealmObject.class);
}

@Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}

8. android okhttp post json和get有什麼區別

區別是:
Get:是以實體的方式得到由請求URI所指定資源的信息,如果請求URI只是一個數據產生過程,那麼最終要在響應實體中返回的是處理過程的結果所指向的資源,而不是處理過程的描述。
Post:用燃游晌來向目的伺服器發出請求,要求它接受被附在請求後的實體,並把它磨棗當作請求隊列中請求URI所指定資源的附加新子項,Post被設計成用統一的方法實現下列功能:
1:對現有資源的解釋
2:向電子公告欄、新聞組、郵件列表或類似討論組發信息。
3:提交數據塊
4:通過附加操作來擴展資料庫

Android系統提供了兩種HTTP通信類,HttpURLConnection和HttpClient。
關於HttpURLConnection和HttpClient的選擇>>官方博客
盡管Google在大部分安卓版本皮鋒中推薦使用HttpURLConnection,但是這個類相比HttpClient實在是太難用,太弱爆了。
OkHttp是一個相對成熟的解決方案,據說Android4.4的源碼中可以看到HttpURLConnection已經替換成OkHttp實現了。所以我們更有理由相信OkHttp的強大。

OkHttp 處理了很多網路疑難雜症:會從很多常用的連接問題中自動恢復。如果您的伺服器配置了多個IP地址,當第一個IP連接失敗的時候,OkHttp會自動嘗試下一個IP。OkHttp還處理了代理伺服器問題和SSL握手失敗問題。
使用 OkHttp 無需重寫您程序中的網路代碼。OkHttp實現了幾乎和java.net.HttpURLConnection一樣的API。如果你用了 Apache HttpClient,則OkHttp也提供了一個對應的okhttp-apache 模塊。

9. android用volley怎麼給伺服器發送json

1.下載官網的android SDK(本人用的是eclipse)

2.新建一個android項目:

File->new->andriod Application project

7、下面就是具體的使用post和get請求的代碼:

A:發送get請求如下:

package com.example.xiaoyuantong;

import java.util.HashMap;

import java.util.Iterator;

import org.json.JSONException;

import org.json.JSONObject;

import android.app.Activity;

import android.os.Bundle;

import android.util.Log;

import android.widget.TextView;

import com.android.volley.Request;

import com.android.volley.RequestQueue;

import com.android.volley.Response;

import com.android.volley.VolleyError;

import com.android.volley.toolbox.JsonObjectRequest;

import com.android.volley.toolbox.Volley;

/**

* Demo

*/

public class MainActivity extends Activity {

private RequestQueue requestQueue ;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

init();

}

private void init() {

TextView textView = (TextView)findViewById(R.id.textView);

requestQueue = Volley.newRequestQueue(this);

getJson();

textView.setText("hello");

}

private void getJson(){

String url = "http://192.168.20.1:8080/xiaoyuantong/userAction!register.action?pwd='測試'";

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(

Request.Method.GET, url, null,

new Response.Listener<JSONObject>() {

@Override

public void onResponse(JSONObject response) {

//這里可以列印出接受到返回的json

Log.e("bbb", response.toString());

}

}, new Response.ErrorListener() {

@Override

public void onErrorResponse(VolleyError arg0) {

// System.out.println("sorry,Error");

Log.e("aaa", arg0.toString());

}

});

requestQueue.add(jsonObjectRequest);

}

}

B:發送post請求如下:

package com.example.xiaoyuantong;

import java.util.HashMap;

import java.util.Map;

import org.json.JSONException;

import org.json.JSONObject;

import com.android.volley.Request;

import com.android.volley.RequestQueue;

import com.android.volley.Response;

import com.android.volley.VolleyError;

import com.android.volley.toolbox.JsonObjectRequest;

import com.android.volley.toolbox.Volley;

import android.os.Bundle;

import android.app.Activity;

import android.util.Log;

import android.view.Menu;

import android.widget.TextView;

public class PostActivity extends Activity {

private RequestQueue requestQueue ;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_post);

init();

}

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.post, menu);

return true;

}

private void init() {

TextView textView = (TextView)findViewById(R.id.postView);

requestQueue = Volley.newRequestQueue(this);

getJson();

textView.setText("hellopost");

}

private void getJson(){

String url = "http://192.168.20.1:8080/xiaoyuantong/userAction!reg.action";

JsonObjectRequest jsonObjectRequest ;

JSONObject jsonObject=new JSONObject() ;

try {

jsonObject.put("name", "張三");

jsonObject.put("sex", "女");

} catch (JSONException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

}

//列印前台向後台要提交的post數據

Log.e("post",jsonObject.toString());

//發送post請求

try{

jsonObjectRequest = new JsonObjectRequest(

Request.Method.POST, url, jsonObject,

new Response.Listener<JSONObject>() {

@Override

public void onResponse(JSONObject response) {

//列印請求後獲取的json數據

Log.e("bbb", response.toString());

}

}, new Response.ErrorListener() {

@Override

public void onErrorResponse(VolleyError arg0) {

// System.out.println("sorry,Error");

Log.e("aaa", arg0.toString());

}

});

requestQueue.add(jsonObjectRequest);

} catch (Exception e) {

e.printStackTrace();

System.out.println(e + "");

}

requestQueue.start();

}

}

8、在android的logcat裡面能查看到列印的請求

(紅色的顯示的是我在後台請求到數據)

有時候logcat顯示不出數據,可能是消息被過濾了,可以在左邊點擊「減號」刪除過濾

在server端,也就是在myeclipse的建立的另一個後台工程裡面能獲取到請求:


9、後續會補充json數據的解析部分,以及過度到移動雲的部分,上面只是c/s模式下的一個簡單的基於http的請求應答例子。

10. android h5返回json怎麼解析

JSON的定義:

一種輕量級的數據交換格式,具有良好的可讀和便於快速編寫的特性。業內主流技術為其提供了完整的解決方案(有點類似於正則表達式 ,獲得了當今大部分語言的支持),從而可以在不同平台間進行數據交換。JSON採用兼容性很高的文本格式,同時也具備類似於C語言體系的行為。 – Json.org
JSON Vs XML

1.JSON和XML的數據可讀性基本相同
2.JSON和XML同樣擁有豐富的解析手段
3.JSON相對於XML來講,數據的體積小
4.JSON與JavaScript的交互更加方便
5.JSON對數據的描述性比XML較差
6.JSON的速度要遠遠快於XML.

Tomcat安裝:

Tomcat下載地址http://tomcat.apache.org/ 下載後安裝,如果成功,啟動Tomcat,然後在瀏覽器里輸入:http://localhost:8080/index.jsp,會有個Tomcat首頁界面,

新建一個android工程JsonDemo.

[java] view plain


package com.tutor.jsondemo;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;

/**
* @author frankiewei.
* Json封裝的工具類.
*/
public class JSONUtil {

private static final String TAG = "JSONUtil";

/**
* 獲取json內容
* @param url
* @return JSONArray
* @throws JSONException
* @throws ConnectionException
*/
public static JSONObject getJSON(String url) throws JSONException, Exception {

return new JSONObject(getRequest(url));
}

/**
* 向api發送get請求,返回從後台取得的信息。
*
* @param url
* @return String
*/
protected static String getRequest(String url) throws Exception {
return getRequest(url, new DefaultHttpClient(new BasicHttpParams()));
}

/**
* 向api發送get請求,返回從後台取得的信息。
*
* @param url
* @param client
* @return String
*/
protected static String getRequest(String url, DefaultHttpClient client) throws Exception {
String result = null;
int statusCode = 0;
HttpGet getMethod = new HttpGet(url);
Log.d(TAG, "do the getRequest,url="+url+"");
try {
//getMethod.setHeader("User-Agent", USER_AGENT);

HttpResponse httpResponse = client.execute(getMethod);
//statusCode == 200 正常
statusCode = httpResponse.getStatusLine().getStatusCode();
Log.d(TAG, "statuscode = "+statusCode);
//處理返回的httpResponse信息
result = retrieveInputStream(httpResponse.getEntity());
} catch (Exception e) {
Log.e(TAG, e.getMessage());
throw new Exception(e);
} finally {
getMethod.abort();
}
return result;
}

/**
* 處理httpResponse信息,返回String
*
* @param httpEntity
* @return String
*/
protected static String retrieveInputStream(HttpEntity httpEntity) {

int length = (int) httpEntity.getContentLength();
//the number of bytes of the content, or a negative number if unknown. If the content length is known but exceeds Long.MAX_VALUE, a negative number is returned.
//length==-1,下面這句報錯,println needs a message
if (length < 0) length = 10000;
StringBuffer stringBuffer = new StringBuffer(length);
try {
InputStreamReader inputStreamReader = new InputStreamReader(httpEntity.getContent(), HTTP.UTF_8);
char buffer[] = new char[length];
int count;
while ((count = inputStreamReader.read(buffer, 0, length - 1)) > 0) {
stringBuffer.append(buffer, 0, count);
}
} catch (UnsupportedEncodingException e) {
Log.e(TAG, e.getMessage());
} catch (IllegalStateException e) {
Log.e(TAG, e.getMessage());
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
return stringBuffer.toString();
}
}

熱點內容
編程與數學 發布:2025-05-20 11:01:23 瀏覽:442
asp連接遠程資料庫 發布:2025-05-20 10:50:20 瀏覽:389
一般電腦配置哪個好 發布:2025-05-20 10:40:58 瀏覽:602
我的世界擼樹伺服器 發布:2025-05-20 10:33:37 瀏覽:740
ftp搭建win7 發布:2025-05-20 10:06:06 瀏覽:82
訪問堅果 發布:2025-05-20 10:06:02 瀏覽:394
ftpxlight 發布:2025-05-20 10:05:22 瀏覽:111
java的實驗報告 發布:2025-05-20 10:02:06 瀏覽:528
豪華配置高電動轎車有哪些 發布:2025-05-20 10:01:59 瀏覽:487
哪些電腦配置低 發布:2025-05-20 09:34:16 瀏覽:955