繁体   English   中英

如何在 Android 上用 retrofit 解析 json

[英]How to parse json with retrofit on Android

我尝试编写解析缩写解码及其使用频率的应用程序。 用户输入缩写,例如“kg”。 所以,应用程序应该连接到“http://nactem.ac.uk/software/acromine/dictionary.py?sf=kg”并解析它。

model 类应该是什么样的? 我在界面中正确描述了@Geth 吗? 如何获取列表,我做了一个适配器,将它绑定到列表,但我不确定getResponse()。

界面:

public interface SService {

@GET("dictionary.py?")
Call<Example> getResponse(@Query("sf=") String searchString);
}

Retrofit客户端:

public class RetrofitClient {

private static Retrofit retrofit = null;

public static Retrofit getClient(String baseUrl) {
    if (retrofit==null) {
        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
}
}

并添加 class ApiUtils

public class ApiUtils {

public static final String BASE_URL = "http://nactem.ac.uk/software/acromine/";

public static SService getSOService() {
    return RetrofitClient.getClient(BASE_URL).create(SService.class);
}
}

主要活动

public class MainActivity extends AppCompatActivity {
private ArrayList<Lf> elements = new ArrayList();
EditText editText1;
ElementAdapter stateAdapter;
ListView list;
private SService mService;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    editText1 = (EditText) findViewById(R.id.edit_text);

    mService = ApiUtils.getSOService();

    list = (ListView) findViewById(R.id.fragment_list);
    
    stateAdapter = new ElementAdapter(this, R.layout.list_item, elements);
    
    list.setAdapter(stateAdapter);
}




public void loadAnswers() {
    mService.getResponse(editText1.getText().toString()).enqueue(new Callback<Example>() {
        @Override
        public void onResponse(Call<Example> call, Response<Example> response) {

            if(response.isSuccessful()) {
                stateAdapter.updateAnswers(response.body().getLfs());
            } else {
                int statusCode = response.code();
                // handle request errors depending on status code
            }
        }

        @Override
        public void onFailure(Call<Example> call, Throwable t) {

        }
    });
}


public void activity_button(View view) {
    //stateAdapter.clear();
    loadAnswers();
}
}

更新:。 所有输入数据都是一个数组。 数组[对象{..:}]。 解析它的正确接口: public interface SService {

@GET("dictionary.py")
Call<List<Example>> getResponse(@Query("sf") String searchString);
}

因此,我们得到了带有示例 object 的调用列表(在这种情况下只有一个 object)。

SService接口更改为以下内容,

public interface SService {

@GET("dictionary.py")
Call<Example> getResponse(@Query("sf") String searchString);
}

暂无
暂无

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

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