当前位置:首页 » 安卓系统 » android解析本地json

android解析本地json

发布时间: 2023-06-12 05:52:44

⑴ Android怎么解析这个json

java">

importjava.util.Iterator;
importjava.util.Map.Entry;
importjava.util.Set;

importcom.google.gson.JsonArray;
importcom.google.gson.JsonElement;
importcom.google.gson.JsonObject;
importcom.google.gson.JsonParser;

publicclassJU
{
publicstaticvoidmain(String[]args)
{
Stringjson=
"{"showapi_res_code":0,"showapi_res_error":"","showapi_res_body":{"ret_code":0,"basic":{"explains":["n.技术;工艺;术语"]}}}";
JsonParserparser=newJsonParser();
JsonObjectobj=(JsonObject)parser.parse(json);
System.out.println(obj);
dir(obj);
}

privatestaticvoiddir(Objectobj)
{
if(objinstanceofJsonObject)
{
JsonObjectobject=(JsonObject)obj;
Set<Entry<String,JsonElement>>entry=object.entrySet();
Iterator<Entry<String,JsonElement>>it=entry.iterator();
while(it.hasNext())
{
Entry<String,JsonElement>elem=it.next();
Stringkey=elem.getKey();
JsonObjectoob;
try
{
oob=(JsonObject)elem.getValue();
System.out.println(key+"--->"+oob);
dir(oob);
}
catch(Exceptione)
{
JsonElementelement=elem.getValue();
System.out.println(key+"--->"+element);
dir(element);
}
}
}
elseif(objinstanceofJsonArray)
{
JsonArrayarray=(JsonArray)obj;
for(inti=0;i<array.size();i++)
{
JsonElementelement=array.get(i);
System.out.print(element+"");
dir(element);
}
}
}
}

⑵ Android读取本地json文件的方法

本文实例讲述了Android读取本地json文件的方法。分享给大家供大家参考,具体如下:

1、读取本地JSON ,但是显示汉字乱码

public static String readLocalJson(Context context, String fileName){ String jsonString=""; String resultString=""; try { BufferedReader bufferedReader=new BufferedReader(new InputStreamReader( context.getResources().getAssets().open(fileName))); while ((jsonString=bufferedReader.readLine())!=null) { resultString+=jsonString; } } catch (Exception e) { // TODO: handle exception } return resultString;}

2、读取本地JSON,显示汉字正确,txt文件设置时UTF-8,UNIX

public static String readLocalJson(Context context, String fileName){ String jsonString=""; String resultString=""; try { InputStream inputStream=context.getResources().getAssets().open(fileName); byte[] buffer=new byte[inputStream.available()]; inputStream.read(buffer); resultString=new String(buffer,"GB2312"); } catch (Exception e) { // TODO: handle exception } return resultString;}

⑶ 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();
}
}

⑷ android json解析成map格式

先看json数据
之前使用的是gson解析,把 discount 写成Object格式,但是通过解析之后转成String类型,成为

这种明显没有办法解析成map集合
使用原始的Json解析,一层一层的找到这个对象,转成String类型成为

这种情况下就可以了 之后是的解析方法
第一种方法是

第二种是

这样就可以获取到map集合了

⑸ android如何从网页中获取一个json数组并解析出来,显示在textview里面

1,先要建立一个线程获取json数据
2接着解析json数据
3,设置textview
例如:json数据,strjson= {"key": ["a","b"]}
JSONObject object = new JSONObject (strjson)
JSONArray arr= object.getJSONArray("key") ;
String text=arr.getString(0);

⑹ Android 如何引用本地json文件

有时候遇到要一些模拟数据的时候,要么写个List<T>,要么写死.

然后数据比较多的时候可以引用本地资源文件,记录下如何使用本地json文件

<1>在java同级目录下创建"assets"资源文件夹

<2>编辑json文本内容
至于json文件夹内容 就自定义了,想要什么内容写什么,对于一个做项目多了的开发者而言 json数据是熟悉到不能再熟悉的了
以下是我在淘宝一个个复制过来自己拼装的一些商品数据

不需要加任何标识,只需要标准的json数据格式就可以了

<3>引用和json解析的工具类,解析用的 Gson也是经常用到的

<4>最后在需要的地方引用,"ExchangeBean"是根据json内容写的一个模型,用于接收存放数据

有时间再补上demo,下面是效果图:

⑺ android 用JSON 解析数据接口方法

接口获取下来的数据为

{"status":200,"message":"查询成功","data":{"id":32,"user_id":null,"user_code":null,"user_pass":null,"meeting_id":"1","meeting_pass":null,"config_param_ip":"11.1.1.70","port":"6501","web_config_param_ip":"11.1.1.70","web_port":"6501","unit_code":null,"create_time":null,"update_time":null,"status":0,"userCode":"video1","userPass":"video1","meetingId":"1","meetingPass":"","apiPort":"13000","username":"admin","password":"123456","updateTime":"2021-11-08 17:45:29"}}

使用方法

try {

    JSONObject jsonObject = new JSONObject(outstring);

    int resultCode = jsonObject.getInt("status");

    if (resultCode == 200) {

        JSONObject obj = jsonObject.getJSONObject("data");

        IP = obj.getString("config_param_ip");

        port = obj.getString("web_port");

        username = obj.getString("userCode");

        password = obj.getString("userPass");

        roomID = Integer.parseInt(obj.getString("meetingId"));

        roomPassword = obj.getString("password");

    } else {

        ToastUtils.showShort("查询失败");

    }

    goVideo();

} catch (Exception e) {

    e.printStackTrace();

}

⑻ 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;
}

⑼ 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());

⑽ android 在服务器端生成json格式数据,在客户端怎么解析

1、生成JSON格式数据,有对应的后台类处理,如果你是做Android开发,后台提供获取数据的接口


2、客户端解决:

JSONArrayjsonArr=newJSONArray(json);
for(inti=0;i<jsonArr.length();i++){
JSONObjectjsonObj=jsonArr.getJSONObject(i);
booleanisChild=jsonObj.has("childrenNodes");
AreaBeanbean=newAreaBean(jsonObj.getString("id"),
jsonObj.getString("parentId"),
jsonObj.getString("name"));
mList.add(bean);
if(isChild){
mchildNodesList.add(jsonObj.getString("childrenNodes"));
}else{
mchildNodesList.add(null);
}
}
热点内容
java分隔 发布:2025-02-08 07:15:02 浏览:810
源码乘法竖式 发布:2025-02-08 07:05:48 浏览:136
天天酷跑脚本脚本精灵 发布:2025-02-08 07:05:15 浏览:345
ios数据库迁移 发布:2025-02-08 07:00:16 浏览:850
安卓sdl是什么 发布:2025-02-08 07:00:05 浏览:907
脱机脚本怎么写 发布:2025-02-08 06:59:22 浏览:832
java学习价钱 发布:2025-02-08 06:58:39 浏览:957
如何用服务器提交ms作业 发布:2025-02-08 06:58:03 浏览:160
c语言的打印函数 发布:2025-02-08 06:43:54 浏览:788
海康威视局域网访问 发布:2025-02-08 06:41:16 浏览:966