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!.