解析json有三种不同的方式
1.原生态的解析json
2.Gson解析json
3.FastJson解析Json
首先看看一条简单的Json数据
解析之后的结果
下面就来看看三种不同解析方式的代码
package com.thm.android_parsejson;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void parseJson(View view){
//01.获取网络json
new MyTask().execute();
}
class MyTask extends AsyncTask{
@Override
protected Object doInBackground(Object[] params) {
try {
URL url = new URL(getString(R.string.server_name)+"person.json");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//设置请求方式
connection.setRequestMethod("GET");
//设置耗时操作
connection.setConnectTimeout(5000);
//获取结果码
int code = connection.getResponseCode();
if(code==200){
InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String str = null;
StringBuffer stringBuffer = new StringBuffer();
while((str=br.readLine())!=null){
stringBuffer.append(str);
}
Log.i("test",stringBuffer.toString());
//02.解析Json
//01.使用原生态的方式
// JSONObject jsonObject = new JSONObject(stringBuffer.toString());
// int list = jsonObject.getInt("list");
// Log.i("test","长度是:"+list);
//
// JSONArray jsonArray = jsonObject.getJSONArray("persons");
//
// for (int i = 0; i <jsonArray.length() ; i++) {
// JSONObject object = jsonArray.getJSONObject(i);
// int pid = object.getInt("pid");
// String pname = object.getString("pname");
// int page = object.getInt("page");
// Log.i("test",pid+" "+pname+" "+page);
// }
// 02.使用Gson解析json
// Gson gson = new Gson();
// BigPerson bigPerson = gson.fromJson(stringBuffer.toString(),BigPerson.class);
// Log.i("test",bigPerson.getList()+"");
//
// List<SmallPerson> persons=bigPerson.getPersons();
// for (SmallPerson person : persons) {
// Log.i("test",person.toString());
// }
// 03.FastJson解析Json
BigPerson bigPerson = JSON.parseObject(stringBuffer.toString(),BigPerson.class);
Log.i("test",bigPerson.getList()+"");
List<SmallPerson> persons=bigPerson.getPersons();
for (SmallPerson person : persons) {
Log.i("test",person.toString());
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// catch (JSONException e) {
// e.printStackTrace();
// }
return null;
}
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
}
}
}
后面两种方法需要去网上找Jar包,还要在Manifests中配置网络权限