什么是json
json是一种与开发语言无关的、轻量级的数据格式。全称JavaScript Object Notation.
优点: 易于人的阅读和编写,易于程序解析与生产
-
一个简单的JSON样例
{ "name":"JSON快速入门(java版本)", "autor":"李广", "content":["JSON基础入门","常用JSON处理"], "time":{ "value":30, "unit":"分钟" } }
-
数据结构-Object
使用花括号{}包含的键值对结构,key必须是string类型,value为任何基本类型或数据结构
-
数据结构-Array
使用中括号[]来起始,并用逗号,来分隔元素
-
json例子
{ "name":"王小二", "age":25.2, "birthday":"1992-11-01", "school":"蓝翔", "major":["理发","挖掘机"], "has_girlfriend":false, "car":null, "house":null, "comment":"这是一个注释" } 1)Android原生技术 特点:编程相对麻烦,但是是Google官方提供的,有些JSON数据必须要Android原生技术来解析。Google官方没有提供将Java转换成json数据的API 数据之间转换: (1)将JSON格式的字符串{}转换成Java对象 API:JSONObject(String json):将json字符串解析为json对象 Xxx getXxx (String name):根据name,在.json对象中得到对应的value Xxx optXxx (String json):根据name,在.json对象中得到对应的value get和opt的区别而:optXxx会在对应的key中的值不存在的时候返回一个空字符串或者你指定的默认值,而getString会出现空指针异常的错误 (2)将JSON格式的字符串[]转换成Java对象的List API:JSONArray(String json):将json字符串解析为json数组 int length ():得到json数组中元素的个数 Xxx getXxx (String name):根据name,在.json对象中得到对应的value Xxx optXxx (String json):根据name,在.json对象中得到对应的value get和opt的区别而:optXxx会在对应的key中的值不存在的时候返回一个空字符串或者你指定的默认值,而getString会出现空指针异常的错误 (3)复杂json的数据解析 (4)特殊json的数据解析
效果
代码:
package com.junjie.jsondemo;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
import com.junjie.jsondemo.adapter.NewsAdapter;
import com.junjie.jsondemo.entity.Tngou;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xml.sax.helpers.LocatorImpl;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private Handler mHandler;
private List<Tngou> tngouList;
private ListView listView;
private NewsAdapter newsAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.lv_list);
mHandler = new Handler(new InnerCallBack());
tngouList =new ArrayList<>();
newsAdapter =new NewsAdapter(this,tngouList);
listView.setAdapter(newsAdapter);
}
public void doClick(View v) {
String url = "http://www.tngou.net/api/top/classify";
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Message message = new Message();
message.what = 0;
String string = response.body().string();
message.obj = string;
mHandler.sendMessage(message);
}
});
}
private class InnerCallBack implements Handler.Callback {
@Override
public boolean handleMessage(Message msg) {
if (msg.what == 0) {
String content = (String) msg.obj;
analysisJsonContent(content);
}
return false;
}
}
/**
* 解析json
*
* @param content
*/
private void analysisJsonContent(String content) {
try {
List<Tngou> tngous =new ArrayList<>();
JSONObject rootObject = new JSONObject(content);
boolean status = rootObject.getBoolean("status");
JSONArray tngou = rootObject.getJSONArray("tngou");
Tngou tngou1 =null;
for (int i = 0; i < tngou.length(); i++) {
tngou1 = new Tngou();
JSONObject jsonObject = tngou.getJSONObject(i);
tngou1.setDescription(jsonObject.getString("description"));
tngou1.setTitle(jsonObject.getString("title"));
tngou1.setId(jsonObject.getInt("id"));
tngou1.setKeywords(jsonObject.getString("keywords"));
tngou1.setName(jsonObject.getString("name"));
tngou1.setSeq(jsonObject.getInt("seq"));
tngous.add(tngou1);
}
tngouList.clear();
tngouList.addAll(tngous);
newsAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
adapter中
package com.junjie.jsondemo.adapter;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.junjie.jsondemo.R;
import com.junjie.jsondemo.entity.Tngou;
import java.util.List;
public class NewsAdapter extends BaseAdapter<Tngou> {
public NewsAdapter(Context context, List<Tngou> list) {
super(context, list);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (viewHolder == null) {
viewHolder = new ViewHolder();
convertView = getInflater().inflate(R.layout.item_news_list, null);
viewHolder.tvId = (TextView) convertView.findViewById(R.id.tv_id);
viewHolder.tvDescription = (TextView) convertView.findViewById(R.id.tv_description);
viewHolder.tvKeywords = (TextView) convertView.findViewById(R.id.tv_keywords);
viewHolder.tvName = (TextView) convertView.findViewById(R.id.tv_name);
viewHolder.tvSeq = (TextView) convertView.findViewById(R.id.tv_seq);
viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tv_title);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
Tngou tngou = getList().get(position);
viewHolder.tvTitle.setText(tngou.getTitle());
viewHolder.tvDescription.setText(tngou.getDescription());
viewHolder.tvName.setText(tngou.getName());
viewHolder.tvId.setText(tngou.getId() + "");
viewHolder.tvSeq.setText(tngou.getSeq() + "");
viewHolder.tvKeywords.setText(tngou.getKeywords());
return convertView;
}
class ViewHolder {
TextView tvId;
TextView tvDescription;
TextView tvKeywords;
TextView tvName;
TextView tvSeq;
TextView tvTitle;
}
}
package com.junjie.jsondemo.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import java.util.ArrayList;
import java.util.List;
public abstract class BaseAdapter<T> extends android.widget.BaseAdapter {
private Context context;
private LayoutInflater inflater;
private List<T> list;
public BaseAdapter(Context context, List<T> list) {
this.context = context;
setList(list);
inflater = LayoutInflater.from(context);
}
public LayoutInflater getInflater() {
return inflater;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
if (list == null) {
list = new ArrayList<>();
}
this.list = list;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
}
实体类
package com.junjie.jsondemo.entity;
public class Tngou {
private String description;
private int id;
private String keywords;
private String name;
private int seq ;
private String title;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getKeywords() {
return keywords;
}
public void setKeywords(String keywords) {
this.keywords = keywords;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSeq() {
return seq;
}
public void setSeq(int seq) {
this.seq = seq;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public String toString() {
return "Tngou{" +
"description='" + description + '\'' +
", id=" + id +
", keywords='" + keywords + '\'' +
", name='" + name + '\'' +
", seq=" + seq +
", title='" + title + '\'' +
'}';
}
}