从响应Retrofit获取单个JSON值

时间:2017-10-05 14:45:54

标签: android json retrofit retrofit2

我试图使用Retrofit从JSON获取单个值,我遵循了一个教程,但是我得到一个错误说"从Callback派生的类匿名类必须被声明...." 。 我特意尝试实现的是在String Axe = "";之类的空字符串中回显单个json属性值,并使用来自服务器的json文件中的特定值填充它。这是我试过的。

Json格式

"axe1": {"test1"}

ApiInterface

import com.google.gson.JsonObject;

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

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

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

所以,我希望将json axe1的值(test1)解析并放入空字符串

2 个答案:

答案 0 :(得分:3)

您使用了错误的导入:

import com.android.volley.Response;

将其替换为

import retrofit2.Response;

答案 1 :(得分:1)

首先,您的JSON格式无效,应为{“axe1”:“test1”}。

要存储它,您可以这样做:

Idle => transitioning to Busy