JSON数据与JSON在android中的应用
来源:互联网 发布:python 创建对象 编辑:程序博客网 时间:2024/05/19 20:20
如题。Json数据与Json在android开发中的应用。
首先。我们先来了解一下什么是Json数据、以及Json数据与xml的区别
当然这是个人理解。大牛勿喷。如有错误、欢迎指正
什么是Json数据 :
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于JavaScript(Standard ECMA-262 3rd Edition - December 1999)的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。这些特性使JSON成为理想的数据交换语言。易于人阅读和编写,同时也易于机器解析和生成。
以上解释来自百度百科
http://baike.baidu.com/link?url=CvKNmMk9gEavL76vWVF_zTVpjgMFZuU0vObvVjqKDu-xqKxjGZuN_tM95re-emsV
大概就是。Json是一种用来数据交换、传递等方便的、易于理解、解释的一串字符串
Json 包含两种数据格式。一种是JsonObject 一种是 JsonArray
也就是一种是Json对象。一种是Json数组。
先来看看JsonObject的格式(示例)
{"key":"value","key1":"value1"...}
类似的就是JsonObject格式的数据。下面是一个JsonObject的数据
{"id":1,"name":"张三","sex":"男","age":18}
这就是一个标准的JsonObject数据。为了大家看的更明白我给换行显示了。
Json数据最外层使用一堆“{}”来包围。中间就是我们需要传递、使用的数据。在Json中。所有的数据都被封装成"key":value 这种形式。其中 key必须是String类型。也就是key必须是一个字符串(两边带双引号“”)。。。这个字符串我就不用说了。
他的value 值。可以是基本数据类型、String类型字符串、JsonObject、JsonArray。比如value可以是一个int的10 也可以是一个字符串的"sky"
这很类似java中的Map结构。key 对应 value 只是Json有上述的数据类型的限制。应为Json只是字面意义的传递数据。而java的Map结构是可以保存任意数据类型的。
好了以上就是Json数据的其中的一种 JsonObject 也就是Json对象,是不是很简单呢? 有童鞋就问了。那另一种JsonArray 也就是Json数组是怎么回事呢?别急。接下来我们就看Json数据的另一种 JsonArray 也就是Json数组。
还是先来看看JsonArray的格式(示例)
{"key":[{"key":value,"key1":value1, ...},{"key":value,"key1":value1, ...}]}
类似的就是JsonArray 。可能上面的一时没有看明白。那看看下面这个比较直接的
{
"teachers":[
{ "id":1,"name":"张老师","sex":"男"},
{ "id":2,"name":"刘老师","sex":"女"},
{ "id":3,"name":"王老师","sex":"男"}
],
"student":[
{ "id":1,"name":"张三","sex":"男"},
{ "id":2,"name":"李四","sex":"女"},
{ "id":3,"name":"王五","sex":"男"}
],
"address":[
"大连",
"昆明",
"长春"
]
}
这样的在一个key对应的value是被[]包围的就是JsonArray。
JsonArray的每个元素都可以是一个value(包括基本数据类型、String、JsonObject、JsonArray)。每一个JsonObject都包含一条具体的数据。
Json数据是一个很自由的数据结构。你可以在JsonObject中将一个value定义为JsonArray。你也可以在JsonArray中定义JsonObject。同时还在JsonArray中再次定义新的JsonArray。所以。在java中数组能保存的数据Json也能保存。Java数组不能保存的数据。Json也能保存。 。Json是不是很强大!他可以为你做任何字面值得数据的数据交换、保存、传递。
好了。知道了Json的数据结构。那么我们就要看看在Android中如何解析Json数据。ps:听到 解析XXX 是不是某同学有想到了令人头痛的几种解析XML的方法。看的眼花缭乱。Json解析。是不是也是非常麻烦啊?? 你今天学习了Json。我可以非常肯定的告诉在android程序中解析Json数据。非常简单!的确!非常简单。
下面我们就来学习在android中如何解析Json数据。
首先。我们来解析JsonObject 先来看看我们需要解析的JsonObject。就拿上面的示例来解析吧。
{
"id":1,
"name":"张三",
"sex":"男",
"age":18
}
准备好了Json数据。我们就来创建android项目。来实际的解析Json数据。
首先创建一个工程。在xml界面布局文件中添加一个TextView。
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <TextView android:id="@+id/txtview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /></LinearLayout>
MainActivity.javapackage com.example.jsonobjectdemo;import org.json.JSONException;import org.json.JSONObject;import android.app.Activity;import android.os.Bundle;import android.widget.TextView;public class MainActivity extends Activity{ private TextView tv; //应为是手动写出来。所以字符串中间的双引号需要用\来转义 String jsonString = "{\"id\":1,\"name\":\"张三\",\"sex\":\"男\",\"age\":18}"; UserBean user; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //获取TextView的引用 tv = (TextView) findViewById(R.id.txtview); //创建Bean user = new UserBean(); //调用解析Json数据的方法 parseJsonObject(); //将解析的结果设置到TextView中 tv.setText("" + user.toString()); } private void parseJsonObject() { try { /** * 根据JsonObject 创建一个JsonObject的java对象, * 有异常。需要try catch * */ JSONObject jsonObject = new JSONObject(jsonString); /** * 获取数据的时候。根据value的值得数据类型。来使用不同的get * 如果一个key的value是String类型。那么就用 * String value = JsonObject.getString(key); * 类似的如果一个key的value是int类型。就用 * int value = JsonObject.getInt(key); * * */ //获取一个int类型的id int id = jsonObject.getInt("id"); //获取String类型的name String name = jsonObject.getString("name"); //获取String类型的sex String sex = jsonObject.getString("sex"); //获取int类型的age int age = jsonObject.getInt("age"); //将获取到的数据放入bean user.setId(id); user.setName(name); user.setSex(sex); user.setAge(age); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
UserBean.javapackage com.example.jsonobjectdemo;import android.R.id;public class UserBean{
private int id;private String name;private String sex;private int age;public int getId(){return id;}public void setId(int id){this.id = id;}public String getName(){return name;}public void setName(String name){his.name = name;}public String getSex(){return sex;}public void setSex(String sex){this.sex = sex;}public int getAge(){return age;}public void setAge(int age){this.age = age;}@Overridepublic String toString(){return "UserBean [id=" + id + ", name=" + name + ", sex=" + sex + ", age=" + age + "]";
}
}
好了。上面就是一个简单的JsonObject解析的过程。代码很简单。
下面我们来解析JsonArray
同样。先写出JsonArray的数据。
{
"users":[
{"id":1,"name":"luci","sex":"女","love":["吃东西","睡懒觉","看电影"]},
{"id":2,"name":"jack","sex":"男","love":["玩游戏","打篮球","听歌"]},
{"id":3,"name":"jone","sex":"女","love":["吃零食","看电影","听歌"]},
]
}
创建工程。
具体代码如下
list_item.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <LinearLayout android:layout_width="wrap_content" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center" android:layout_weight="1" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="id:" /> <TextView android:id="@+id/id" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="1" android:gravity="center" /> </LinearLayout> <LinearLayout android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:orientation="vertical" android:gravity="center_vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="name:"/> <TextView android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="jack"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="sex"/> <TextView android:id="@+id/sex" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="男"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="love:"/> <TextView android:id="@+id/love" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="玩游戏,打篮球,听歌"/> </LinearLayout></LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <ListView android:id="@+id/listview" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/hello_world" /></LinearLayout>
MainActivity.javapackage com.example.jsonarraydemo;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.AdapterView;import android.widget.AdapterView.OnItemClickListener;import android.widget.ListView;import android.widget.SimpleAdapter;import android.widget.Toast;public class MainActivity extends Activity{ //JsonArray格式的字符串。应为卸载一起双引号的缘故。所以都在双银行上加了转义字符\ private String jsonArray = "{\"users\":[{\"id\":1,\"name\":\"luci\",\"sex\":\"女\",\"love\":[\"吃东西\",\"睡懒觉\",\"看电影\"]},{\"id\":2,\"name\":\"jack\",\"sex\":\"男\",\"love\":[\"玩游戏\",\"打篮球\",\"听歌\"]},{\"id\":3,\"name\":\"jone\",\"sex\":\"女\",\"love\":[\"吃零食\",\"看电影\",\"听歌\"]}]}";
//listviewprivate ListView listview;//listview的数据源private List<Map<String, String>> list;@Overrideprotected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);listview = (ListView) findViewById(R.id.listview);//获取listview的数据源list = parseJsonArray();SimpleAdapter adapter = new SimpleAdapter(this, list, R.layout.listview_item, new String[]{"id","name","sex","love"}, new int[]{R.id.id,R.id.name,R.id.sex,R.id.love});listview.setAdapter(adapter);listview.setOnItemClickListener(new OnItemClickListener(){@Overridepublic void onItemClick(AdapterView<?> listview, View view, int position,long id){/*** 从list数据源中将当前点击的这一条数据取出 应为数据源是List<Map<String, String>>* 所以list集合中的元素都是Map<String, String>* */Map<String, String> map = list.get(position);//从这条数据中获取到他的数据int pid = Integer.parseInt(map.get("id"));String name = map.get("name");String sex = map.get("sex");String love = map.get("love");Toast.makeText(MainActivity.this, "您单击了id=" + pid + " name=" + name + " sex=" + sex + " love=" + love + " 这条数据", Toast.LENGTH_SHORT).show();}});}private List<Map<String, String>> parseJsonArray(){
List<Map<String, String>> li = new ArrayList<Map<String,String>>();try{
//创建一个JsonObjectJSONObject jsonObject = new JSONObject(jsonArray);//获取到JsonObject中的JsonArrayJSONArray array = jsonObject.getJSONArray("users");/*** 此时 array这个JsonArray的数据为* [{"id":1,"name":"luci","sex":"女","love":["吃东西","睡懒觉","看电影"]},{"id":2,"name":"jack","sex":"男","love":["玩游戏","打篮球","听歌"]},{"id":3,"name":"jone","sex":"女","love":["吃零食","看电影","听歌"]}]* 每个元素都是一个JsonObject。所以应该用一下的方式解析这个(注意。是这个)JsonArray* *///遍历JsonArray。取出所有的数据for(int x = 0; x < array.length(); x ++){Map<String, String> map = new HashMap<String, String>();//获取到JsonArray中的每一个元素(JsonObject)JSONObject obj = array.getJSONObject(x);//其中的一个 obj 就是 {"id":1,"name":"luci","sex":"女","love":["吃东西","睡懒觉","看电影"]}//从这一个obj中取出数据int id = obj.getInt("id");String name = obj.getString("name");String sex = obj.getString("sex");String love = "";//获取love的值。应为他的值是一个JsonArray。所以解析格式如下JSONArray loveArray = obj.getJSONArray("love");//此时 loveArray 的数据为 ["吃东西","睡懒觉","看电影"]for(int z = 0; z < loveArray.length(); z ++){//因为这时候。loveArray的元素都为String类型。所以我们可以直接取出love+=loveArray.getString(z) + "、";}//将解析到的一条数据放入Map、map.put("id", "" + id);map.put("name", name);map.put("sex", sex);map.put("love", love);//将这一条解析到的数据。放入list集合中li.add(map);}
}catch (JSONException e){// TODO Auto-generated catch blocke.printStackTrace();}//将解析到list集合返回return li;}
}
当然这里用到的是android自带的json解析库。个人感觉有个不好的地方。就是如果解析某个键时。没有找到这个键。就会抛异常。
大家也可以自己到网上找其他的json解析库。比如 google的gson
第一次写博文。代码格式似乎有点不会搞。以后尽量规范代码格式。
0 0
- JSON数据与JSON在android中的应用
- Json数据与Json在android开发中的应用
- JSon在Android中的应用
- Json 在 Android中的应用
- Json数据解析在Unity3d中的应用
- Json数据解析在Unity3d中的应用
- Json数据解析在Unity3d中的应用
- Json数据解析在Unity3d中的应用
- Json数据解析在Unity3d中的应用
- Json数据解析在Unity3d中的应用
- Json数据解析在Unity3d中的应用
- JSON在PHP中的应用
- JSON在PHP中的应用
- JSON在PHP中的应用
- JSON在PHP中的应用
- JSON在PHP中的应用
- JSON在PHP中的应用
- JSON在java中的应用
- Maven中使用本地JAR包
- div仿checkbox表单样式美化及功能
- Spring MVC 3.0.5+Spring 3.0.5+MyBatis3.0.4+FreeMarker全注解实例详解
- mysql迁移到db2实践记录
- 根据情况编写脚本来实现自己特定的一些目标
- JSON数据与JSON在android中的应用
- GitHub Android 最火开源项目Top20
- 百度开启网络广告管理“全免费”新时代——网络收入面临重新洗牌
- socketpair
- php新手上路教程
- XMPPFrameWork IOS 开发(七)消息回执
- nekohtml中解析中出现中文乱码问题
- 程序自删除
- Oracle EBS SLA 详解