Android 从URL解析JSON并获取响应图像\ URL,然后使用ImageLoader打开它
我正在尝试解析从Android应用程序中的URL获取的JSON结果。 我在网上试过几个例子,但都没用。 我的url是:{aff_id}。Android 从URL解析JSON并获取响应图像\ URL,然后使用ImageLoader打开它,android,json,android-intent,android-asynctask,universal-image-loader,Android,Json,Android Intent,Android Asynctask,Universal Image Loader,我正在尝试解析从Android应用程序中的URL获取的JSON结果。 我在网上试过几个例子,但都没用。 我的url是:{aff_id}。 点击url后,JSON数据如下所示: {"success":true, "offer": { "packageName":"com.myntra.android", "campKey":"284", "app_name":" Myntra", "image_url":"https:\/\/media.go2speed.org\/bran
点击url后,JSON数据如下所示:
{"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 - $0.40\r\n50-100 INR - $0.62\r\n100-125 INR - $0.70\r\n125+ - $0.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\u url”响应,然后使用ImageLoader打开image\u url
解析此JSON数据并获取图像url并使用ImageLoader打开它的最简单方法是什么?请帮忙
我的服务代码点击并获取图像\u 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();
}
}
公共类GallectCaView扩展了ImageView{
公共画廊(背景){
超级(上下文);
}
公共目录视图(上下文ctx、属性集集){
超级(ctx,套);
}
public GallecticaView(上下文ctx、属性集、int defStyleAttr){
超级(ctx、set、defStyleAttr);
}
public GallecticaView(上下文ctx、属性集、int-defStyleAttr、int-defStyleRes){
超级(ctx、set、defStyleAttr、defStyleRes);
}
私有静态字符串PREF_NAME=“gallectica_PREF_adstuck”;
私有静态SharedReferences优先级;
私有void initIV(最终上下文ctx){
新建异步任务(){
字符串开发程序\u公钥;
受保护的void onPreExecute(){
super.onPreExecute();
prefs=ctx.getSharedReferences(PREF_名称,Context.MODE_PRIVATE);
prefs.edit().putString(“android”,Settings.Secure.getString(ctx.getApplicationContext().getContentResolver(),Settings.Secure.android)).commit();
developer_public_key=prefs.getString(“developer_public_key”,“23/89533a6f4248873b08ce52ce680f29e7”);
}
受保护的布尔doInBackground(无效…arg0){
字符串json=“”;
HttpURLConnection=null;
InputStream=null;
ArrayList params=新的ArrayList();
add(新的BasicNameValuePair(“aff_id”,prefs.getString(“android_id)”,“”);
添加(新的BasicNameValuePair(“开发者公钥”,开发者公钥));
试一试{
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(“http://a.nextput.com/api/single-offer/“+developer\u public\u key+”/a“;//您的URL?aff\u id
HttpResponse HttpResponse=httpClient.execute(httpPost);
json=EntityUtils.toString(httpResponse.getEntity());
JSONObject jObj=新的JSONObject(json);
boolean issucess=jObj.getBoolean(“成功”);
System.out.println(“成功:+issucess”);
/*JSONObject JSONObject=新的JSONObject(json);
boolean state=jsonObject.getBoolean(“成功”)*/
ImageLoaderConfiguration配置=新建ImageLoaderConfiguration.Builder(ctx)
.threadPriority(Thread.NORM_PRIORITY-2)
.DenycacheMageMultipleSizesInMemory()
.diskCacheFileNameGenerator(新的Md5FileNameGenerator())
.diskCacheSize(50*1024*1024)//50 Mb
.tasksProcessingOrder(QueueProcessingType.LIFO)
//.writeDebugLogs()//删除发布应用程序
.build();
//使用配置初始化ImageLoader。
ImageLoader.getInstance().init(配置);
返回成功;
}捕获(例外e){
Log.e(“JSON解析器”,“错误解析数据”+e.toString());
}
返回false;
}
受保护的void onPostExecute(布尔结果){
super.onPostExecute(结果);
//ImageLoader.getInstance().displayImage(imageUrl);
}
}.execute();
}
}
如何在其中获取图像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上述设置图像的方法是通过通用图像加载程序库,如中所示,您只需使用Gson库即可。只需在build.gradle中添加依赖项,并创建一个pojo文件,该文件将常量化所有json变量及其getter和setter 编译'com.google.code.gson:gson:2.2.4' 列表=新的ArrayList(); JSONObject jsonRootObject=新的JSONObject(Stringjson) jsonResult=jsonRootObject.getString(“成功”) if(jsonResult.equalsIgnoreCase(“true”)){ JsonObject offerbj=jsonRootObject.getJSONObject(“offer”) list=new Gson().fromJson(jsonArray.toString(),new TypeToken>({}.getType()) }
现在,列表中的所有数据都包含响应
JSONObject offerJson = reponse.getJSONObject("offer");
String imageUrl = offerJson.getString("image_url");
现在您有了图像url,可以使用任何imageloader将该url中的图像显示到任何ImageView中
您可以使用Glide、毕加索或UniversalImageLoader。这三个是著名的。使用Gson库自动解析json响应,前提是您需要有与响应匹配的适当模型类。 然后使用ImageLoader从url下载图像。步骤: 步骤1:首先使用JSON解析获取要显示的图像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;
///*** 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();
}
}
使用下面提到的JsonParser类:
公共类JSONParser{
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响应获取imageUrl:
JSONObject jobject=新的JSONObject(“您的Json响应”);
JSONObject jo=jobject.getJSONObject(“offer”)
字符串imageUrl=jo.getString(“image_url”)
步骤2:现在可以使用毕加索库将此图像url加载到Imageview。这是从url加载图像的最佳方法之一
从这里获取毕加索jar文件
步骤3:使用代码加载图像U