草庐IT

android - 从 Retrofit 响应中获取单个 JSON 值

coder 2023-12-28 原文

我试图使用 Retrofit 从 JSON 获取单个值,我遵循了一个教程,但我收到一条错误消息,指出“必须声明从回调派生的类匿名类......”。 我特别想要实现的是在一个空字符串中回显单个 json 属性值,如 String Ax = ""; 我用来自服务器的 json 文件的特定值填充它。这是我尝试过的。

Json格式

"axe1": {"test1"}

Api 接口(interface)

import com.google.gson.JsonObject;

import retrofit2.Call;
import retrofit2.http.GET;

public interface ApiInterface {
@GET("test.json")
Call<JsonObject> readJsonFromFileUri();
}

主要 Activity

 import android.graphics.Typeface;
 import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;


import com.android.volley.Response;

import com.google.gson.Gson;
import com.google.gson.JsonObject;


import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


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;
// URL of object to be parsed
// This string will hold the results
String data = "";
class Myads{
    String bnr;
    String intt;
}
@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));
    }

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://yourdomain.com/s/  ")
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    ApiInterface apiInterface = retrofit.create(ApiInterface.class);

    Call<JsonObject> jsonCall = apiInterface.readJsonFromFileUri();
    jsonCall.enqueue(new Callback<JsonObject>() {
        @Override
        public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
            JsonObject json = new JsonObject(body().toString());
            Gson gson = new Gson();
            Myads ad = gson.fromJson(jsonString, Myads.class);
            Log.i(LOG_TAG, String.valueOf(ad.bnr));
        }

                         @Override
                         public void onFailure(Call<JsonObject> call, Throwable t) {
                             Log.e(LOG_TAG, t.toString());
                         }

                     });


    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", "allQuotes");
            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", "isFavorite");
            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", "qteday");
            startActivity(qteDay);
        }
    });

    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();
        }
    });




}


@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);
}
}

所以,我想解析 test1 的 Json axe1 的值并将其放入空字符串中

最佳答案

您使用了错误的导入:

import com.android.volley.Response;

替换为

import retrofit2.Response;

关于android - 从 Retrofit 响应中获取单个 JSON 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46588533/

有关android - 从 Retrofit 响应中获取单个 JSON 值的更多相关文章

  1. ruby-on-rails - Rails HTML 请求渲染 JSON - 2

    在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这

  2. ruby - 简单获取法拉第超时 - 2

    有没有办法在这个简单的get方法中添加超时选项?我正在使用法拉第3.3。Faraday.get(url)四处寻找,我只能先发起连接后应用超时选项,然后应用超时选项。或者有什么简单的方法?这就是我现在正在做的:conn=Faraday.newresponse=conn.getdo|req|req.urlurlreq.options.timeout=2#2secondsend 最佳答案 试试这个:conn=Faraday.newdo|conn|conn.options.timeout=20endresponse=conn.get(url

  3. ruby-on-rails - 每次我尝试部署时,我都会得到 - (gcloud.preview.app.deploy) 错误响应 : [4] DEADLINE_EXCEEDED - 2

    我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie

  4. ruby - 从 Ruby 中的主机名获取 IP 地址 - 2

    我有一个存储主机名的Ruby数组server_names。如果我打印出来,它看起来像这样:["hostname.abc.com","hostname2.abc.com","hostname3.abc.com"]相当标准。我想要做的是获取这些服务器的IP(可能将它们存储在另一个变量中)。看起来IPSocket类可以做到这一点,但我不确定如何使用IPSocket类遍历它。如果它只是尝试像这样打印出IP:server_names.eachdo|name|IPSocket::getaddress(name)pnameend它提示我没有提供服务器名称。这是语法问题还是我没有正确使用类?输出:ge

  5. ruby - 获取模块中定义的所有常量的值 - 2

    我想获取模块中定义的所有常量的值:moduleLettersA='apple'.freezeB='boy'.freezeendconstants给了我常量的名字:Letters.constants(false)#=>[:A,:B]如何获取它们的值的数组,即["apple","boy"]? 最佳答案 为了做到这一点,请使用mapLetters.constants(false).map&Letters.method(:const_get)这将返回["a","b"]第二种方式:Letters.constants(false).map{|c

  6. ruby-on-rails - 获取 inf-ruby 以使用 ruby​​ 版本管理器 (rvm) - 2

    我安装了ruby​​版本管理器,并将RVM安装的ruby​​实现设置为默认值,这样'哪个ruby'显示'~/.rvm/ruby-1.8.6-p383/bin/ruby'但是当我在emacs中打开inf-ruby缓冲区时,它使用安装在/usr/bin中的ruby​​。有没有办法让emacs像shell一样尊重ruby​​的路径?谢谢! 最佳答案 我创建了一个emacs扩展来将rvm集成到emacs中。如果您有兴趣,可以在这里获取:http://github.com/senny/rvm.el

  7. Ruby 从大范围中获取第 n 个项目 - 2

    假设我有这个范围:("aaaaa".."zzzzz")如何在不事先/每次生成整个项目的情况下从范围中获取第N个项目? 最佳答案 一种快速简便的方法:("aaaaa".."zzzzz").first(42).last#==>"aaabp"如果出于某种原因你不得不一遍又一遍地这样做,或者如果你需要避免为前N个元素构建中间数组,你可以这样写:moduleEnumerabledefskip(n)returnto_enum:skip,nunlessblock_given?each_with_indexdo|item,index|yieldit

  8. ruby - Net::HTTP 获取源代码和状态 - 2

    我目前正在使用以下方法获取页面的源代码:Net::HTTP.get(URI.parse(page.url))我还想获取HTTP状态,而无需发出第二个请求。有没有办法用另一种方法做到这一点?我一直在查看文档,但似乎找不到我要找的东西。 最佳答案 在我看来,除非您需要一些真正的低级访问或控制,否则最好使用Ruby的内置Open::URI模块:require'open-uri'io=open('http://www.example.org/')#=>#body=io.read[0,50]#=>"["200","OK"]io.base_ur

  9. ruby-on-rails - 如何使用 Rack 接收 JSON 对象 - 2

    我有一个非常简单的RubyRack服务器,例如:app=Proc.newdo|env|req=Rack::Request.new(env).paramspreq.inspect[200,{'Content-Type'=>'text/plain'},['Somebody']]endRack::Handler::Thin.run(app,:Port=>4001,:threaded=>true)每当我使用JSON对象向服务器发送POSTHTTP请求时:{"session":{"accountId":String,"callId":String,"from":Object,"headers":

  10. ruby - 没有类方法获取 Ruby 类名 - 2

    如何在Ruby中获取BasicObject实例的类名?例如,假设我有这个:classMyObjectSystem我怎样才能使这段代码成功?编辑:我发现Object的实例方法class被定义为returnrb_class_real(CLASS_OF(obj));。有什么方法可以从Ruby中使用它? 最佳答案 我花了一些时间研究irb并想出了这个:classBasicObjectdefclassklass=class这将为任何从BasicObject继承的对象提供一个#class您可以调用的方法。编辑评论中要求的进一步解释:假设你有对象

随机推荐