【Android】解析Json数据

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数据_第1张图片

【Android】解析Json数据_第2张图片

 

你可能感兴趣的:(【Android】解析Json数据)