Android 中详细理解Josn

来源:互联网 发布:淘宝武士盔甲 编辑:程序博客网 时间:2024/06/05 17:52

JSON就是一串字符串 只不过元素会使用特定的符号标注。

特殊的格式:

*{} 双括号表示对象
[] 中括号表示数组
“” 双引号内是属性或值
: 冒号表示后者是前者的值(这个值可以是字符串、数字、也可以是另一个数组或对象)


String str="{\"name\": \"Michael\",\"age\":\"23\""array":[\"aaa\": \"Michael\",\"bb\":\"23\"]}";

所以 可以理解为是一个包含name为Michael的对象
而[{“name”: “Michael”},{“name”: “Jerry”}]就表示包含两个对象的数组

 Json格式:jsons={"name": "zhangsan","sex":"男"}   

{}:用JsonObject
[]: JsonArray


jsonObject ———— 对像或字符串

try{ JSONObject obj=new JSONObject(jsons);     String name=obj.getString("name");    String sex=obj.getString("sex");}   jsons="Array":[{"name":" zhangsan","sex":"男"} ,{"name":" lisi","sex":"女"} ]jsonArray-------------- 指数组try{JSONArray array=new JSONArray("jsons");JSONObject obj=array.getJSONObject(下标);}ex:
package com.cn.testjson;import android.annotation.TargetApi;import android.os.Build;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.util.Log;import android.view.View;import android.widget.TextView;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;public class MainActivity extends AppCompatActivity { private String strJson="{'name':'tom','age':'12',['name':'jack','age':'30']}";  private String str="{\n" +          "    \"name\": \"tom\",\n" +          "    \"age\": \"12\",\n" +          "    \"array\": [\n" +          "        {\n" +          "            \"name\": \"jac\",\n" +          "            \"age\": \"30\"\n" +          "        }\n" +          "    ],\n" +          "    \"json\": {\n" +          "        \"a\": \"11\"\n" +          "    }\n" +          "}";    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        TextView jsonTextView=(TextView)findViewById(R.id.json);        jsonTextView.setOnClickListener(new View.OnClickListener() {            @TargetApi(Build.VERSION_CODES.KITKAT)            @Override            public void onClick(View view) {                try {                    JSONObject jsonObject=new JSONObject(str);                    String name= (String) jsonObject.get("name");                    String age=jsonObject.getString("age");                    Log.e("name===",name);                    Log.e("age===",age);                    //得到一个JsonArray                    JSONArray array= null;//通过JsonObject得到一个JsonArray                        array =jsonObject.getJSONArray("array");                       JSONObject jsonObject1= array.getJSONObject(0);                       String arrayName=jsonObject1.getString("name");                        Log.e("arrayName===",arrayName);                    JSONObject jsonObject2=jsonObject.getJSONObject("json");                             String a= jsonObject2.getString("a");                    Log.e("a===",a);                } catch (JSONException e) {                    e.printStackTrace();                }            }        });    }}

如下Json格式:

{"UserName":"zhuli","age":"30","workIn":"ali","Array":["tom","20","google"]}string str="{\"UserName\":\"ZHULI\",\"age\":\"30\",\"workIn\":\"ALI\",\"Array\":[\"ZHULI\",\"30\",\"ALI\"]}"JsonObject object=new JsonObject(str);String name=object.getString("UserName");try {     JSONObject jsonObject= null;     try {         jsonObject = new JSONObject(str);         String name=jsonObject.getString("UserName");         String ageOne=jsonObject.getString("age");         String job=jsonObject.getString("workIn");         JSONArray jsonArray=jsonObject.getJSONArray("Array");//数组         List list=new ArrayList();         StringBuffer stringBuffer=new StringBuffer();         for(int i=0;i<jsonArray.length();i++){             list.add(jsonArray.get(i));             stringBuffer.append(list.get(i).toString());         }         mtxt.setText(stringBuffer.toString());         Log.i("sst===",sst);     } catch (JSONException e) {         e.printStackTrace();     }
String t="[{\"name\":\" zhangsan\",\"sex\":\"\"} ,{\"name\":\" lisi\",\"sex\":\"\"} ]";private TextView mtxt;@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    mtxt=(TextView)findViewById(R.id.txt1);   // JSONObject jsonObject=new J    try {        JSONArray jsonArray=new JSONArray(t);        JSONObject jsonObject=jsonArray.getJSONObject(0);       String name=jsonObject.getString("name");        mtxt.setText(name);    } catch (JSONException e) {        e.printStackTrace();    }``**`##将josn转换为对象
String str=new Gson.toJson(对像);{"msg":"请求成功","data":{"total":2500,"listPage":[{"date":{"date":30,"hours":18,"seconds":27,"month":7,"nanos":0,"timezoneOffset":-480,"year":116,"minutes":1,"time":1472551287000,"day":2},"amount":1,"product":{"cover":"picture/16082555548.png","price":300,"intro":"tu","name":"交试 30日","isSale":false,"charge_day":"30","id":19,"isNew":false,"category":{"name":"充值卡","id":6},"isShow":false},"total":300,"id":43,"user":{"password":"KLhV3KchnkHG1Vo/a8ZHRQ==","code":"","repassword":"","phone":"13146245969","id":6,"username":"13146245969"}},{"date":{"date":30,"hours":18,"seconds":25,"month":7,"nanos":0,"timezoneOffset":-480,"year":116,"minutes":1,"time":1472551285000,"day":2},"amount":1,"product":{"cover":"picture/16082545604.png","price":1500,"intro":"emv","name":"测试 30日","isSale":false,"charge_day":"30","id":20,"isNew":false,"category":{"name":"充值卡","id":6},"isShow":false},"total":1500,"id":42,"user":{"password":"KLhV3KchnkHG1Vo/a8ZHRQ==","code":"","repassword":"","phone":"13146245969","id":6,"username":"13146245969"}},{"date":{"date":30,"hours":18,"seconds":23,"month":7,"nanos":0,"timezoneOffset":-480,"year":116,"minutes":1,"time":1472551283000,"day":2},"amount":1,"product":{"cover":"picture/16082532494.png","price":700,"intro":"tck","name":"30日","isSale":false,"charge_day":"30","id":21,"isNew":false,"category":{"name":"充值卡","id":6},"isShow":false},"total":700,"id":41,"user":{"password":"KLhV3KchnkHG1Vo/a8ZHRQ==","code":"","repassword":"","phone":"13146245969","id":6,"username":"13146245969"}}]},"status":0}{ "people": [{ "userName": "Brett", "content":"聊天内容", "time": "当前时间" },{ "userName": "tom", "content":"聊天内容", "time": "当前时间" },{ "userName": "jack", "content":"聊天内容", "time": "当前时间" },{ "userName": "tomcat", "content":"聊天内容", "time": "当前时间" },]}
/* try {     JSONObject jsonObject=new JSONObject(string);     String name=jsonObject.getString("userName");     JSONArray jsonArray=jsonObject.getJSONArray("Array");//得到的是数组      Person person=new Person();     person.setUserName(jsonArray.get(0).toString());     person.setAge(jsonArray.get(1).toString());     person.setJob(jsonArray.get(2).toString()); } catch (JSONException e) {     e.printStackTrace(); }// Gson gson=new Gson();*/
{ "people": [{ "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },{ "firstName": "Jason", "lastName":"Hunter", "email": "bbbb"},{ "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" }]}

一个大括号对应一个实体类

如果是[]对应的是一个数组或者一个List 此数组 /list 类型是里面内容决定
最外层的Json

UsetTalk==={ List <Talk>people}  Talk{}{ "people": [“1",“2”]}A最外层的实体类{   List <String> people}

希望对你们有一些帮助!

原创粉丝点击