当前位置:首页 » 安卓系统 » 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 05:45:30 浏览:926
阿里云的服务器修建在哪里 发布:2025-05-20 05:44:49 浏览:770
网盘存储文件 发布:2025-05-20 05:32:05 浏览:245
linux网卡的mac 发布:2025-05-20 05:31:13 浏览:7
手机照相机文件夹 发布:2025-05-20 05:29:49 浏览:848
数控车床电脑编程软件 发布:2025-05-20 05:29:42 浏览:966
智能pos如何下载安卓 发布:2025-05-20 05:29:08 浏览:343
防病毒源码 发布:2025-05-20 05:25:00 浏览:927
小米自动上传 发布:2025-05-20 05:06:06 浏览:625
王者荣耀引流脚本 发布:2025-05-20 05:06:03 浏览:486