从 URL 解析 JSON 并获取响应 image_url 并使用 ImageLoader 打开它

Parse JSON from URL and get the response image_url and open it using ImageLoader

我正在尝试解析从我的 Android 应用中的 URL 获取的 JSON 结果。 我已经在 Internet 上尝试了几个示例,但无法正常工作。 我的 url 是:http://a.nextput.com/api/single-offer/23/89533a6f4248873b08ce52ce680f29e7/a?aff_id={aff_id}.
JSON 数据在点击 url 后看起来像这样:

{"success":true,
 "offer":
 {  
  "packageName":"com.myntra.android",
  "campKey":"284",
  "app_name":" Myntra",
  "image_url":"https:\/\/media.go2speed.org\/brand\/files\/wadogo\/142\/thumbnails_100\/unnamed-3.png",
  "desc1":"No Incent\r\nNo Free-Recharge apps traffic\r\nNO SMS\r\nNo Email\r\nNo Adult traffic\r\nNo Bot Traffic\r\nKPI - purchase% >10% of Total Installs. If not met, CPI payout will be pro-rata.\r\nNote: No social media traffic allowed. No traffic from Datalead.\r\n\r\nThe caps provided are network wide. \r\nPlease ask AM for individual Caps by Mail and Skype.\r\nexpiry date: TBA\r\nThe offer will stop converting once we hit the daily\/monthly cap\r\nCPI per install\r\nOnly use the creatives provided by us.\r\n\r\nPayout Slab:\r\n0-10 INR - Nill\r\n10-50 INR - [=13=].40\r\n50-100 INR - [=13=].62\r\n100-125 INR - [=13=].70\r\n125+ - [=13=].90",
  "desc2":null,
  "rdata":"[]",
  "cats":"0",
  "banner_url":"https:\/\/www.google.co.in\/logos\/doodles\/2016\/dmitri-mendeleevs-182nd-birthday-5692309846884352-hp.jpg",
  "click_url":"http:\/\/a.nextput.com\/apps\/install-begin\/284\/23\/37693cfc748049e45d87b8c7d8b9aacd\/89533a6f4248873b08ce52ce680f29e7\/u?aff_id={aff_id}",
  "country":"IN",
  "payout":0.12 }}

我必须解析此 JSON 并获得 "image_url" 响应并使用 ImageLoader 打开 image_url。

解析此 JSON 数据并获取 image_url 并使用 ImageLoader 打开它的最简单方法是什么?请帮忙!!!

我的服务代码命中并获得 image_url:

public class GallecticaView extends ImageView {

public GallecticaView(Context context){
    super(context);
}

public GallecticaView(Context ctx, AttributeSet set) {
    super(ctx, set);
}

public GallecticaView(Context ctx, AttributeSet set, int defStyleAttr) {
    super(ctx, set, defStyleAttr);
}

public GallecticaView(Context ctx, AttributeSet set, int defStyleAttr, int defStyleRes) {
    super(ctx, set, defStyleAttr, defStyleRes);
}

private static String PREF_NAME = "gallectica_pref_adstuck";
private static SharedPreferences prefs;

private void initIV(final Context ctx) {
    new AsyncTask<Void, Void, Boolean>() {
        String developer_public_key;

        protected void onPreExecute() {
            super.onPreExecute();
            prefs = ctx.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
            prefs.edit().putString("android_id", Settings.Secure.getString(ctx.getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID)).commit();

            developer_public_key = prefs.getString("developer_public_key", "23/89533a6f4248873b08ce52ce680f29e7");
        }

        protected Boolean doInBackground(Void... arg0) {
            String json = "";
            HttpURLConnection connection = null;
            InputStream is = null;

            ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("aff_id", prefs.getString("android_id", "")));
            params.add(new BasicNameValuePair("developer_public_key", developer_public_key));


            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost("http://a.nextput.com/api/single-offer/" + developer_public_key + "/a");//YOUR URL  ?aff_id

                HttpResponse httpResponse = httpClient.execute(httpPost);
                json = EntityUtils.toString(httpResponse.getEntity());

                JSONObject jObj = new JSONObject(json);
                boolean isSuccess = jObj.getBoolean("success");
                System.out.println("success : " + isSuccess);

                /* JSONObject jsonObject = new JSONObject(json);
                   boolean state = jsonObject.getBoolean("success");*/

                ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(ctx)
                        .threadPriority(Thread.NORM_PRIORITY - 2)
                        .denyCacheImageMultipleSizesInMemory()
                        .diskCacheFileNameGenerator(new Md5FileNameGenerator())
                        .diskCacheSize(50 * 1024 * 1024) // 50 Mb
                        .tasksProcessingOrder(QueueProcessingType.LIFO)
                                //.writeDebugLogs() // Remove for release app
                        .build();
                // Initialize ImageLoader with configuration.
                ImageLoader.getInstance().init(config);

                return isSuccess;
            } catch (Exception e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }

            return false;
        }

        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);

          //  ImageLoader.getInstance().displayImage(imageUrl);
        }
    }.execute();

}
}

如何在其中获取 image_url 响应并使用 ImageLoader 在 imageview 中加载它?

假设您得到的 JSON 响应是结果

ImageLoader imageLoader = ImageLoader.getInstance();
if(result.getBoolean("success")){
    JSONObject offer = result.getJSONObject("offer");
    String imageUrl = offer.getString("image_url");
    imageLoader.displayImage(imageUri, yourImageView);
}

其中yourImageView是你要设置图片的图片视图

P.S 上述设置图像的方式是通过通用图像加载库,如 https://github.com/nostra13/Android-Universal-Image-Loader

你可以简单地使用 Gson 库。只需在 build.gradle 中添加依赖项并创建一个 pojo 文件,该文件常量所有 json 变量及其 getter 和 setter.

编译'com.google.code.gson:gson:2.2.4'

List list = new ArrayList(); JSONObject jsonRootObject = new JSONObject(Stringjson);

json结果 = jsonRootObject.getString("success");

if(jsonResult.equalsIgnoreCase("true")){

JsonObject offerObj = jsonRootObject.getJSONObject("offer");

list = new Gson().fromJson(jsonArray.toString(), new TypeToken>(){}.getType());

}

现在您列表中的所有数据..enjoy

JSONObject response = 包含响应。

JSONObject offerJson = reponse.getJSONObject("offer");
String imageUrl = offerJson.getString("image_url");

现在您有了图像 url,您可以使用任何图像加载器将此 url 中的图像显示到任何 ImageView 中。

您可以使用 Glide、Picasso 或 UniversalImageLoader。这3个是有名的。

使用自动解析您的 json 响应的 Gson 库,前提是您需要具有与响应匹配的正确模型 class。 然后使用 ImageLoader 从 url.

下载图像

步骤:

步骤 1 : 首先使用 [= 获取要显示的图像 url 72=]解析.

使用下面提到的Json解析器class:

public class JSON解析器{

InputStream is = null;
 JSONObject jObj = null;
 String json = "";

 // constructor
 public JSONParser() {
 }

 public String getJSONFromUrl(String url) {

  // Making HTTP request
  try {

   DefaultHttpClient httpClient = new DefaultHttpClient();
   HttpPost httpPost = new HttpPost(url);
   HttpResponse httpResponse = httpClient.execute(httpPost);
   Log.e("response", "" + httpResponse);

   HttpEntity httpEntity = httpResponse.getEntity();
   is = httpEntity.getContent();

  } catch (UnsupportedEncodingException e) {
   e.printStackTrace();
  } catch (ClientProtocolException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  try {
   BufferedReader reader = new BufferedReader(new InputStreamReader(
     is, "iso-8859-1"), 8);
   StringBuilder sb = new StringBuilder();
   String line = null;
   while ((line = reader.readLine()) != null) {
    sb.append(line + "\n");
   }
   json = sb.toString();
   is.close();
  } catch (Exception e) {
   Log.e("Buffer Error", "Error converting result " + e.toString());
  }
  return json;
 }

}

使用下面的代码从 Json 中获取图像Url 响应:

JSONObject jobject = new JSONObject("Your Json Response"); JSON对象 jo = jobject.getJSONObject("offer");

字符串图片Url = jo.getString("image_url");

第 2 步: 现在可以使用 Picasso 库将此图像 url 加载到 Imageview。这是从 url 加载图像的最佳方式之一。

从这里获取 Picasso jar 文件

http://square.github.io/picasso/

第三步:使用代码加载图片Url using Picasso

//初始化ImageView ImageView imageView = (ImageView) findViewById(R.id.imageView);

//从url下方加载图片到imageView

Picasso.with(这个) .load("YOUR IMAGE URL HERE") .into(imageView);

根据您的要求,这是您 class 中的更改: 请检查并告诉我。

 public class GallecticaView extends ImageView {

public GallecticaView(Context context){
    super(context);
}

public GallecticaView(Context ctx, AttributeSet set) {
    super(ctx, set);
}

public GallecticaView(Context ctx, AttributeSet set, int defStyleAttr) {
    super(ctx, set, defStyleAttr);
}

public GallecticaView(Context ctx, AttributeSet set, int defStyleAttr, int defStyleRes) {
    super(ctx, set, defStyleAttr, defStyleRes);
}

private static String PREF_NAME = "gallectica_pref_adstuck";
private static SharedPreferences prefs;

private void initIV(final Context ctx) {
    new AsyncTask<Void, Void, Boolean>() {
        String developer_public_key;


        ///*** CODE ADDED BY NEW CODER ***/////
        String imageUrl; 

        protected void onPreExecute() {
            super.onPreExecute();
            prefs = ctx.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
            prefs.edit().putString("android_id", Settings.Secure.getString(ctx.getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID)).commit();

            developer_public_key = prefs.getString("developer_public_key", "23/89533a6f4248873b08ce52ce680f29e7");
        }

        protected Boolean doInBackground(Void... arg0) {
            String json = "";
            HttpURLConnection connection = null;
            InputStream is = null;

            ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("aff_id", prefs.getString("android_id", "")));
            params.add(new BasicNameValuePair("developer_public_key", developer_public_key));


            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost("http://a.nextput.com/api/single-offer/" + developer_public_key + "/a");//YOUR URL  ?aff_id

                HttpResponse httpResponse = httpClient.execute(httpPost);
                json = EntityUtils.toString(httpResponse.getEntity());

                JSONObject jObj = new JSONObject(json);
                boolean isSuccess = jObj.getBoolean("success");
                System.out.println("success : " + isSuccess);

                /* JSONObject jsonObject = new JSONObject(json);
                   boolean state = jsonObject.getBoolean("success");*/


                   //// *** CODE ADDED BY NEW CODER *** ////
                   JSONObject jObject = jObj.getJSONObject("offer");
                   imageUrl =   jObject.getString("image_url");



                return isSuccess;
            } catch (Exception e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }

            return false;
        }

        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);

            if(isSuccess)
            {
                Picasso.with(this).load(imageUrl).into("Your ImageVIew");
            }

          //  ImageLoader.getInstance().displayImage(imageUrl);
        }
    }.execute();

}
}