android解析json对象
❶ android怎样解析Json并列序列的数组
[["北京市"],["上海市"],["合肥市","芜湖市","蚌端口市"]] 这是一个JsonArray ,先获取JsonArray对象,然后再次获取获取JsonArray对象:子JsonArray对象=父JsonArray对象.get(index值);最后,获取子JsonArray对象里面的数据,子JsonArray对象.get(index值);
❷ android中使用java解析json数据
这个格式使用如下代码解析
try{
JSONObjectjsonObject=newJSONObject(json);
JSONObjectweatherinfo=jsonObject.getJSONObject("weatherinfo");
System.out.println(weatherinfo.getString("city"));
System.out.println(weatherinfo.getString("cityid"));
System.out.println(weatherinfo.getString("temp"));
System.out.println(weatherinfo.getString("WD"));
}catch(JSONExceptione){
e.printStackTrace();
}
其中第一行代码JSONObjectjsonObject=newJSONObject(json);//json即为你的字符串
比如现在天气信息是多个城市的,并非只有北京市。
{"weatherinfo":[{"city":"北京","cityid":"101010100","temp":"4","WD":"东风","WS":"2级","SD":"75%","WSE":"2","time":"10:45","isRadar":"1","Radar":"JC_RADAR_AZ9010_JB","njd":"暂无实况","qy":"1011"},{"city":"天津","cityid":"101010100","temp":"4","WD":"东风","WS":"2级","SD":"75%","WSE":"2","time":"10:45","isRadar":"1","Radar":"JC_RADAR_AZ9010_JB","njd":"暂无实况","qy":"1011"}]}
以下代码适用。
try{
JSONObjectjsonObject=newJSONObject(json);
JSONArrayjsonArray=jsonObject.getJSONArray("weatherinfo");
for(inti=0;i<jsonArray.length();i++){
JSONObjectobject=jsonArray.getJSONObject(i);
System.out.println(object.getString("city"));
System.out.println(object.getString("cityid"));
System.out.println(object.getString("temp"));
System.out.println(object.getString("WD"));
}
}catch(JSONExceptione){
e.printStackTrace();
}
❸ Android Json 解析
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=
"[{"MaterielNum":"RQ17017111715","SupplyName":"hahaha","QualityMateriel":"RQ17017111715","RuKuNum":80,"QualityCount":20,"QualityResult":[{"CheckProjectName":"外观","CheckResult":1,"UnQualifiedCount":30,"CheckDetails":[{"ItemCheckName":"外观","ItemCheckValue":50},{"ItemCheckName":"外观1","ItemCheckValue":20},{"ItemCheckName":"外观2","ItemCheckValue":30}]},{"CheckProjectName":"尺寸","CheckResult":0,"UnQualifiedCount":31,"CheckDetails":[{"ItemCheckName":"尺寸","ItemCheckValue":10},{"ItemCheckName":"尺寸2","ItemCheckValue":20},{"ItemCheckName":"尺寸3","ItemCheckValue":30}]},{"CheckProjectName":"标识","CheckResult":1,"UnQualifiedCount":10,"CheckDetails":[{"ItemCheckName":"标识","ItemCheckValue":10},{"ItemCheckName":"标识2","ItemCheckValue":20}]}]}]";
JsonParserparser=newJsonParser();
JsonElementobj=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还有用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使用Gson解析网络接口返回的Json数据
Gson挺好用的,可以把json串直接解析成bean对象,或者把对象转换成json串,数据解析的时候先创建Gson对象
GsonmGson=newGson();
然后再把json串解析成bean对象
Beanbean=mGson.fromJson(json,Bean.class);
如果想把对象转成json串可以用gson的toJson方法
Stringjson=mGson.toJson();
纯手打,满意请采纳
❻ 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文件解析为类对象 出现以下错误,求解答。
用Gson解析json数据是可以的, 如果你非要把解析对象写成类嵌套的形式,就必须要参考gson的用户指南.这是截图:
:最好的办法是不要用类嵌套. 直接写两个类接即可
public class LoginData {
public Data Data;
public String Detail;
public string Return;
}
public static class Data {
public String name;
private String token;
public int uid;
}
❽ Android 解析json问题
///http地址
StringhttpUrl=ip+":"+端口号+"/loginbyandroid/validate.do";
//HttpPost连接对象
HttpPosthttpRequest=newHttpPost(httpUrl);
//使用NameValuePair来保存要传递的Post参数
List<NameValuePair>params=newArrayList<NameValuePair>();
//添加要传递的参数
params.add(newBasicNameValuePair("loginId","value"));
params.add(newBasicNameValuePair("password","value"));
//设置字符集
HttpEntityhttpentity;
try{
httpentity=newUrlEncodedFormEntity(params,"utf-8");
//请求httpRequest
httpRequest.setEntity(httpentity);
//取得默认的HttpClient
HttpClienthttpclient=newDefaultHttpClient();
//取得HttpResponse
HttpResponsehttpResponse;
httpResponse=httpclient.execute(httpRequest);
//HttpStatus.SC_OK表示连接成功
if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
//取得返回的字符串
StringstrResult=EntityUtils.toString(httpResponse
.getEntity());
JSONArrayjsonArray=newJSONArray(strResult);
for(inti=0;i<jsonArray.length();i++){
JSONObjectjsonObject=(JSONObject)jsonArray.opt(i);
Stringsuccess=jsonObject.getString("success");
StringJSESSIONID=jsonObject.getString("JSESSIONID");
StringloginName=jsonObject.getString("loginName");
Stringorgname=jsonObject.getString("orgname");
System.out.println("success="+success
+"JSESSIONID="+JSESSIONID+"loginName="
+loginName+"orgname="+orgname);
}
}else{
System.out.println("请求错误!");
}
}catch(ClientProtocolExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
❾ android 三层json数据解析
这个逻辑很简单的。
先把整个字符串对象从网上获取,并做trim()处理。
然后根据这个字符串新建jsonObject
在从这个object中根据key“Data”获取数组getJsonArray()
在看这个数组中有2个对象。
final int length = jsonarray.length();
从长度为length的for循环中获取每个json对象jsonarray.getindex(i);
就跟剥皮一样,一层一层的剥下去就哦了。
so easy!.