从JSON获取值

时间:2014-01-03 04:06:04

标签: android json jsonobject

我是android的新手。我需要从web服务获取值。这里我使用了json解析。输出的Json格式是{“flag”:0}。在这里,我需要采取标志的值,并使用该值,我想开始另一种方法。我如何取得旗帜的价值。请帮我。我用这种方式。

public String objectvalue(String result){

    try {
        JSONObject obj=new JSONObject(result);

            String flag=obj.getString("flag");
            mString=flag;
            System.out.println(mString);


    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }



    return mString;
}

但我没有得到flag的值。这个参数结果是从server.ie输出的,结果= {“flag”:0}

4 个答案:

答案 0 :(得分:0)

您可以尝试使用AsyncTask来解决问题。它是获取JSON数据的最佳和优先方式

像这样定义AsyncTask ..

new BussinessOwnerHttpAsyncTask().execute();

和您的AsyncTask类..

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

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();

        // Progress dialog code goes over here ..

        pDialog = new ProgressDialog(getParent());
        pDialog.setMessage("Please wait ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {

        //  Maintaining Shared preferences class for further...

        HttpClient httpclient = new DefaultHttpClient();

        String myUrl = Your_url_goes_over_here;


        String encodedURL = "";
        try {
            encodedURL = URLEncoder.encode(myUrl, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try {
            URL url = new URL(encodedURL);
            Log.d("asca", ""+url);
        } catch (MalformedURLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        Log.i("url", city_name + "~" + country_name);
        Log.d("location", request_url+encodedURL);
        HttpGet httpget = new HttpGet(request_url+encodedURL);

        try {
            httpresponse = httpclient.execute(httpget);
            System.out.println("httpresponse" + httpresponse);
            Log.i("response", "Response" + httpresponse);
            InputStream is = httpresponse.getEntity().getContent();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();

            String recievingDataFromServer = null;
            while ((recievingDataFromServer = br.readLine()) != null) {
                Log.i("CHECK WHILE", "CHECK WHILE");
                sb.append(recievingDataFromServer);
            }

            myJsonString = sb.toString();
            Log.d("manish", myJsonString);
            serverSearchData = sb.toString();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return sb.toString();
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        pDialog.dismiss();
        if (myJsonString.length() > 0) {
            try {
                myJsonObject = new JSONObject(myJsonString);

                String your_flag = myJsonObject.getString("flag");

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

    }

}

现在你很高兴接受你的询问..

答案 1 :(得分:0)

{  // JSONObject
   "flag": 0 
}

使用

JSONObject obj=new JSONObject(result);
int flag=obj.getInt("flag");

http://developer.android.com/reference/org/json/JSONObject.html

public int getInt (String name)

Added in API level 1
Returns the value mapped by name if it exists and is an int or can be coerced to an int.

Throws
JSONException   if the mapping doesn't exist or cannot be coerced to an int.

如果这不起作用,您需要发布更多信息。

答案 2 :(得分:0)

“flag”值格式为整数,而不是字符串,这是执行此操作的简单代码:

int flagValues = jsonObject.getInt("flag");
Log.w("values ",String.valuesOf(flagValues));

答案 3 :(得分:0)

首先,mString变量的声明在哪里?我假设它在你的java类中被声明为instance variable,如果不是,请检查。

你有一个格式良好的JSON,形式为

{ "flag": 0 }

所以将其转换为JSONObject应该可以完美运行。

用于提取flag密钥

的值

flag中有一个名为JSONObject的密钥,其值为Integer,您尝试使用getString()方法提取该密钥。

您应该使用以下任一方法调用

optInt(String key)

  

获取与键关联的可选int值,如果没有此键或者该值不是数字,则为零。如果值是字符串,则会尝试将其评估为数字。

int flag = optInt("flag");

OR

optInt(String key, int defaultValue)

  

获取与键关联的可选int值,如果没有此键,则为默认值,或者该值不是数字。如果值是字符串,则会尝试将其评估为数字。

int flag = optInt("flag", 0);

您的代码包含更改

public int objectValue(String result){
    int flag = 0;
    try {
        JSONObject obj=new JSONObject(result);
        flag = obj.optInt("flag");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return flag;
}

编辑:在评论中回答问题。

public String objectValue(String result){
    int flag = 0;
    try {
        JSONObject obj=new JSONObject(result);
        flag = obj.optInt("flag");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return String.valueOf(flag);
}

希望这有帮助。

相关问题