简体   繁体   English

从响应Retrofit获取单个JSON值

[英]Get single JSON value from response Retrofit

Im trying to get a single value from JSON using Retrofit, i followed a tutorial but i got an error saying that "Class anonymous class derived from Callback must be either declared ...." . 我试图使用Retrofit从JSON获取单个值,我按照教程但我得到一个错误,说“从Callback派生的类匿名类必须声明....”。 what im specifically trying to achieve is to echo a single json property value in a empty string like String Axe = ""; 我特别想要实现的是在String Axe = "";类的空字符串中回显单个json属性值String Axe = ""; and i fill it with a specific value from the json file from the server. 我用来自服务器的json文件中的特定值填充它。 here is what i tried. 这是我试过的。

Json format Json格式

"axe1": {"test1"}

The ApiInterface ApiInterface

import com.google.gson.JsonObject;

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

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

The MainActivity MainActivity

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

So, i want the value of Json axe1 which is test1 to be parsed and put in into the empty string 所以,我希望将json axe1(test1)的值解析并放入空字符串中

You are using wrong import: 您使用了错误的导入:

import com.android.volley.Response;

Replace it with 替换为

import retrofit2.Response;

Firstly, your JSON format is invalid, it should be {"axe1": "test1"}. 首先,您的JSON格式无效,它应该是{“axe1”:“test1”}。

To store it you could do : 要存储它你可以做:

JSONObject json = new JSONObject(response.body().toString());   
Log.i(LOG_TAG, json.getString("axe1"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM