从url解析json字符串并将其存储在空字符串中

时间:2017-10-06 15:41:23

标签: android json

我试图解析在线服务器中存在的json字符串并存储在像String data = "";这样的空字符串中,但是当我尝试解析它并且我看到日志时我看到来自服务器的响应当我只需要解析一个特定字符串以存储在空字符串中时,显示所有json代码(括号和引号以及jsonobject)。这是json:

{
"main1": {"bnl":"code"}
}

httphanlder

import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;


public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();

public HttpHandler() {
}

public String makeServiceCall(String reqUrl) {
    String response = null;
    try {
        URL url = new URL(reqUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        // read the response
        InputStream in = new BufferedInputStream(conn.getInputStream());
        response = convertStreamToString(in);
    } catch (MalformedURLException e) {
        Log.e(TAG, "MalformedURLException: " + e.getMessage());
    } catch (ProtocolException e) {
        Log.e(TAG, "ProtocolException: " + e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "IOException: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
    return response;
}

private String convertStreamToString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line).append('\n');
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}
}

,这是主要活动

public class MainActivity extends ActionBarActivity {

DataBaseHandler db;
private AlertDialog dialog;
public static final int IntialQteOfDayId = 8;
private ImageView btn_quotes, btn_authors, btn_favorites, btn_categories, btn_qteday, btn_rateus ;
final Context context = this;
SharedPreferences preferences;
private static final int RESULT_SETTINGS = 1;
private NativeExpressAdView mNativeExpressAdView;
// URL of object to be parsed
// This string will hold the results

private String TAG = MainActivity.class.getSimpleName();
String data = "";
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "https://yourdomain.com/test.json";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
    }
    new GetAd().execute();
    LinearLayout layout = (LinearLayout)findViewById(R.id.layoutId);
    // Create a native express ad. The ad size and ad unit ID must be set before calling
    // loadAd.
    mNativeExpressAdView = new NativeExpressAdView(MainActivity.this);
    mNativeExpressAdView.setAdSize(new AdSize(AdSize.FULL_WIDTH, 90));
    mNativeExpressAdView.setAdUnitId(data);
    // Create an ad request.
    AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
    // Start loading the ad.
    mNativeExpressAdView.loadAd(adRequestBuilder.build());
    // Add the NativeExpressAdView to the view hierarchy.
    layout.addView(mNativeExpressAdView);
    Typeface bold = Typeface.createFromAsset(getAssets(),
            "fonts/extrabold.otf");
    db = new DataBaseHandler(this);
    db.openDataBase() ;
    TextView cat = (TextView) findViewById(R.id.titlecat);
    cat.setTypeface(bold);
    TextView alls = (TextView) findViewById(R.id.titlest);
    alls.setTypeface(bold);
    TextView fav = (TextView) findViewById(R.id.titlefav);
    fav.setTypeface(bold);
    TextView qday = (TextView) findViewById(R.id.titleqday);
    qday.setTypeface(bold);
    TextView rate = (TextView) findViewById(R.id.titleqrate);
    rate.setTypeface(bold);
    btn_quotes = (ImageView) findViewById(R.id.btn_quotes);
    //btn_authors= (Button) findViewById(R.id.btn_authors);
    btn_categories = (ImageView)  findViewById(R.id.btn_categories);
    btn_favorites = (ImageView)  findViewById(R.id.btn_favorites);
    btn_qteday = (ImageView)  findViewById(R.id.btn_qteday);
    btn_rateus = (ImageView)  findViewById(R.id.btn_rateus);

    btn_quotes.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            Intent intent = new Intent(MainActivity.this,
                    QuotesActivity.class);
            intent.putExtra("mode", "alltext");
            startActivity(intent);
        }
    });

    /*btn_authors.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            Intent author = new Intent(MainActivity.this,
                    AuteursActivity.class);
            startActivity(author);
        }
    });*/

    btn_favorites.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            Intent favorites = new Intent(MainActivity.this,
                    QuotesActivity.class);
            favorites.putExtra("mode", "isFav");
            startActivity(favorites);
        }
    });

    btn_categories.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            Intent category = new Intent(MainActivity.this,
                    CategoryActivity.class);
            startActivity(category);
        }
    });

    btn_qteday.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            preferences = PreferenceManager
                    .getDefaultSharedPreferences(context);

            Intent qteDay = new Intent(MainActivity.this,
                    QuoteActivity.class);
            qteDay.putExtra("id",
                    preferences.getInt("id", IntialQteOfDayId));
            qteDay.putExtra("mode", "today");
            startActivity(today);
        }
    });

    btn_rateus.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            AlertDialog.Builder builder = new AlertDialog.Builder(
                    MainActivity.this);
            builder.setMessage(getResources().getString(
                    R.string.ratethisapp_msg));
            builder.setTitle(getResources().getString(
                    R.string.ratethisapp_title));
            builder.setPositiveButton(
                    getResources().getString(R.string.rate_it),
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog,
                                            int which) {
                            // TODO Auto-generated method stub
                            Intent fire = new Intent(
                                    Intent.ACTION_VIEW,
                                    Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName()));           //dz.amine.thequotesgarden"));
                            startActivity(fire);

                        }
                    });

            builder.setNegativeButton(
                    getResources().getString(R.string.cancel),
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog,
                                            int which) {
                            // TODO Auto-generated method stub
                            dialog.dismiss();

                        }
                    });
            dialog = builder.create();
            dialog.show();
        }
    });




}
void startTheThingWithData(){
    //Here data has value
    Log.e(data, data);
}
/**
 * Async task class to get json by making HTTP call
 */
private class GetAd extends AsyncTask<Void, Void, Void> {

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

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        HttpHandler sh = new HttpHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url);



        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);
                JSONObject dataa = jsonObj.getJSONObject("main1");
                String ad =  dataa.getString("bnl");
                data = ad;
                Log.e(TAG, "Response from url: " + ad);


            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }
        } else {
            Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Couldn't get json from server. Check LogCat for possible errors!",
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }

        return null;
    }

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

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.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();

    //noinspection SimplifiableIfStatement
    if (id == R.id.menu_settings) {
        Intent i = new Intent(this, UserSettingActivity.class);
        startActivityForResult(i, RESULT_SETTINGS);
    }

    return super.onOptionsItemSelected(item);
}

这是它在日志中显示的内容

E/MainActivity: Response from url: {

            "main1": {

            "bnl":"code"
            }
}

1 个答案:

答案 0 :(得分:1)

您正在打印jsonStr,而您想要的内容就是数据。

AyncTasks运行async,意味着代码运行paralalel:检查这个简单的示例以获得更好的未完成。

MyModel._meta.get_fields()

上面的代码将调用afterAsyncHere()三次,两次在onCreate中,一次在onPostExecute中。打印结果将是:      来自onCreate的“s”      来自onCreate的“s”      来自onPostExecute的“值b”

请注意,在onPostExecute中,您的任务已结束,并且'b'的值已更新。 在第二次调用中(在启动任务之后),值仍为“s”。

String b = "s"; 
void onCreate(Bundle b) {
   afterAsyncHere();
   new Task().execute();
   afterAsyncHere();
}

void afterAsyncHere() {
   Log.e("onCreate", b);
}

class Task extends AsyncTask {
    Object doInBackground(Object ... args) {
        b ="value b";
        try { Thread.sleep(1000); }catch(Exception e) {}
    }
    void onPostExecute(Object r) {
        afterAsyncHere();
    }
}
}

可行的实际代码是:

  String ad =  dataa.getString("bnl");
  data = ad;
  Log.e(TAG, "Response.data from url: " + data);

注意我在Activity上添加了一个回调方法,并从onPostExecute

调用它