没有从url获取json的输出

时间:2014-07-29 06:48:15

标签: android json parsing

我正在尝试解析json但无法获取。任何人都可以帮我找到如何获得这个:

{
  "firstName": "****",
  "headline": "Software Engineer",
  "id": "Y8gyiQS0gM",
  "lastName": "****",
  "location": {
    "country": {"code": "in"},
    "name": "Bengaluru Area, India"
  },
  "pictureUrl": "",
  "siteStandardProfileRequest": {"url": ""}
}

我使用此代码获取但未在日志中获得任何结果。

DefaultHttpClient httpclient = new DefaultHttpClient();
try {
    HttpGet httpget = new HttpGet("url");

    HttpResponse response = httpclient.execute(httpget);
    String jsonResp=EntityUtils.toString(response.getEntity());
    Log.d("HTTP","Rsponse : "+ jsonResp);

    JSONObject jsonObject = new JSONObject(jsonResp);
    String firstname = jsonObject.getString("firstName");
    String id = jsonObject.getString("id");
    String headline = jsonObject.getString("headline");
    String lastName = jsonObject.getString("lastName");
    //String pictureUrl  = jsonObject2.getString("pictureUrl");

    Log.d("HTTP", "firstname : " + firstname.toString() + "id" + id.toString());
} ...

我已编写此代码以查看用户个人资料。但结果没有得到任何结果。

编辑:

public class ViewProfileActivity extends ListActivity {

Button userProfile;
TextView tv;
private static final String TAG_ID = "id";
private static final String TAG_FNAME = "firstname";
private static final String TAG_LNAME = "lastname";
private static final String TAG_HLINE = "headline";
private static final String TAG_PURL = "pictureUrl";
private static final String TAG_URL = "url";
private ProgressDialog pDialog;
ArrayList<HashMap<String, String>> contactList = null;
 String url="...."

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.view_user);

    userProfile = (Button) findViewById(R.id.view);
    tv=(TextView)findViewById(R.id.textView1);

    userProfile.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            new GetContacts().execute();
        }


        class GetContacts extends AsyncTask<Void, String, Void> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // Showing progress dialog
                pDialog = new ProgressDialog(ViewProfileActivity.this);
                pDialog.setMessage("Please wait...");
                pDialog.setCancelable(false);
                pDialog.show();

            }

            @Override
            protected Void doInBackground(Void... params) {
                DefaultHttpClient httpclient = new DefaultHttpClient();
                try {
                    HttpGet httpget = new HttpGet(
                            "url");
                    HttpResponse response = httpclient.execute(httpget);
                    String jsonResp = EntityUtils.toString(response.getEntity());
                    Log.d("HTTP","Rsponse : "+ jsonResp);

                    JSONObject jsonObject = new JSONObject(jsonResp);
                    String firstname = jsonObject.getString("firstName");
                    String id = jsonObject.getString("id");
                    String headline = jsonObject.getString("headline");
                    String lastname = jsonObject.getString("lastName");
                    String pictureUrl = jsonObject.getString("pictureUrl");
                    JSONObject jsonObject2 = jsonObject
                            .getJSONObject("siteStandardProfileRequest");
                    String url = jsonObject2.getString("url");
                    Log.d("HTTP", "firstname : " + firstname + "\n" + "id :"
                            + id + "\n" + "headline : " + headline + "\n"
                            + "lastName :" + lastname + "\n" + "pictureUrl :"
                            + pictureUrl + "\n" + "Url :" + url);


                    HashMap<String, String> contact = new HashMap<String, String>();
                    contact.put(TAG_ID, id);
                    contact.put(TAG_FNAME, firstname);
                    contact.put(TAG_LNAME, lastname);
                    contact.put(TAG_HLINE, headline);
                    contact.put(TAG_PURL, pictureUrl);
                    contact.put(TAG_URL, url);
                    contactList.add(contact);
                    tv.setText((CharSequence) contactList);

                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                super.onPostExecute(result);
                // Dismiss the progress dialog
                if (pDialog.isShowing())
                    pDialog.dismiss();

                ListAdapter adapter = new SimpleAdapter(
                        LinkedInSampleActivity.this, contactList,
                        R.layout.list_item, new String[] {TAG_URL,TAG_FNAME}, new int[]{R.id.imageView1,R.id.textView1 });
                setListAdapter(adapter);
            }
        }

});
}

}

2 个答案:

答案 0 :(得分:0)

对于解析:
 如果您到达Log.d("HTTP","Rsponse : "+ jsonResp);,则可以使用Gson进行解析。

public class JsonResponseModel {

 String firstName;  
 String lastName;  
 String headline;  
 String id;  
//rest of the fields

//getters setters functions

}

对于模型类中的命名差异(根据webservice中的变量),可以使用类似的注释 @SerializedName

然后,与Gson一起使用:

Gson gson = new Gson();
JsonResponseModel responseModelObject = new JsonResponseModel();
responseModelObject= gson.fromJson(jsonResp, JsonResponseModel.class);   
//now you have the data in responseModelObject

<强> NetworkOnMainThreadException:
为什么我写“如果”你在答案的第一行达到......

使用问题中发布的代码,您可以直接调用网络操作(?),您可能会遇到该异常。

答案 1 :(得分:0)

使用此代码发出HTTP请求(对于您的网址中的url传递)

HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 500);

Client = new DefaultHttpClient(params);
httpget = new HttpGet(url);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
mContent = Client.execute(httpget, responseHandler);

然后使用它来获取您的数据:

JSONObject jsonObject = new JSONObject(mContent);
String firstname = jsonObject.getString("firstName");
String id = jsonObject.getString("id");
String headline = jsonObject.getString("headline");
String lastName = jsonObject.getString("lastName");

注意 ::

  • 对于url您必须传递您尝试的网址 获得JSON响应
  • 同样将上述代码放在Asynchronous task内 崩溃,因为你正在发出网络请求

希望这有帮助!如果您有任何错误,请退回。

{编辑}

public class ViewProfileActivity extends ListActivity {

    Button userProfile;
    TextView tv;
    private static final String TAG_ID = "id";
    private static final String TAG_FNAME = "firstname";
    private static final String TAG_LNAME = "lastname";
    private static final String TAG_HLINE = "headline";
    private static final String TAG_PURL = "pictureUrl";
    private static final String TAG_URL = "url";
    private ProgressDialog pDialog;
    ArrayList<HashMap<String, String>> contactList = null;
     String url="...."

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_user);

        userProfile = (Button) findViewById(R.id.view);
        tv=(TextView)findViewById(R.id.textView1);

        userProfile.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                new GetContacts().execute();
            }


            class GetContacts extends AsyncTask<Void, String, Void> {
                String firstname;
                String id;
                String headline;
                String lastname;
                String pictureUrl;

                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    // Showing progress dialog
                    pDialog = new ProgressDialog(ViewProfileActivity.this);
                    pDialog.setMessage("Please wait...");
                    pDialog.setCancelable(false);
                    pDialog.show();

                }

                @Override
                protected Void doInBackground(Void... params) {
                    DefaultHttpClient httpclient = new DefaultHttpClient();
                    try {
                        HttpGet httpget = new HttpGet(
                                "url");
                        HttpResponse response = httpclient.execute(httpget);
                        String jsonResp = EntityUtils.toString(response.getEntity());
                        Log.d("HTTP","Rsponse : "+ jsonResp);

                        JSONObject jsonObject = new JSONObject(jsonResp);
                        firstname = jsonObject.getString("firstName");
                        id = jsonObject.getString("id");
                        headline = jsonObject.getString("headline");
                        lastname = jsonObject.getString("lastName");
                        pictureUrl = jsonObject.getString("pictureUrl");
                        JSONObject jsonObject2 = jsonObject
                                .getJSONObject("siteStandardProfileRequest");
                        String url = jsonObject2.getString("url");
                        Log.d("HTTP", "firstname : " + firstname + "\n" + "id :"
                                + id + "\n" + "headline : " + headline + "\n"
                                + "lastName :" + lastname + "\n" + "pictureUrl :"
                                + pictureUrl + "\n" + "Url :" + url);


                        HashMap<String, String> contact = new HashMap<String, String>();
                        contact.put(TAG_ID, id);
                        contact.put(TAG_FNAME, firstname);
                        contact.put(TAG_LNAME, lastname);
                        contact.put(TAG_HLINE, headline);
                        contact.put(TAG_PURL, pictureUrl);
                        contact.put(TAG_URL, url);
                        contactList.add(contact);
                        tv.setText((CharSequence) contactList);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(Void result) {
                    super.onPostExecute(result);
                    // Dismiss the progress dialog
                    if (pDialog.isShowing())
                        pDialog.dismiss();

                    ListAdapter adapter = new SimpleAdapter(
                            LinkedInSampleActivity.this, contactList,
                            R.layout.list_item, new String[] {TAG_URL,TAG_FNAME}, new int[]{R.id.imageView1,R.id.textView1 });
                    setListAdapter(adapter);

                    // SET your Text Views here 
                    //
                    //USE the variables stored globally in your Aynnc Class
                    //
                    //
                }
            }

    });
    }
}