首页 > 移动平台 > 详细

【Android】解析Json数据

时间:2015-09-25 00:11:52      阅读:303      评论:0      收藏:0      [点我收藏+]

Json数据:"{\"UserID\":\"Allen\",\"Dep\":IT,\"QQ\":\"969661314\"}"

通过如下代码,将此Json数据转换为Json对象,类似数组一样,然后通过字段名获取每一个值:

package com.example.androidjson;

import org.json.JSONException;
import org.json.JSONObject;
 
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;


public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        
        Button btn=(Button)findViewById(R.id.btnJson);
        
        btn.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                
                 String myjson="{\"UserID\":\"Allen\",\"Dep\":IT,\"QQ\":\"969661314\"}";
                 
                 try {
                    JSONObject json=new JSONObject(myjson);
                    
                    String strUserID=json.getString("UserID");
                    String strDep=json.getString("Dep");
                    String strQQ=json.getString("QQ");
                    
                    TextView txtUserID=(TextView)findViewById(R.id.textView1);
                    TextView txtDep=(TextView)findViewById(R.id.textView2);
                    TextView txtQQ=(TextView)findViewById(R.id.textView3);
                    txtUserID.setText(strUserID);
                    txtDep.setText(strDep);
                    txtQQ.setText(strQQ);
                    
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                 
            }
        });
        
        
        
        
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

技术分享

技术分享

 

【Android】解析Json数据

原文:http://www.cnblogs.com/allen0118/p/4836913.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!