AQuery JSONObject为null

时间:2017-08-26 11:50:25

标签: android json networking aquery

这是我尝试使用的片段的完整代码。我用AQuery来获取json。但我有一个问题。 JsonObject,JsonObject ...总是为空。我在“邮差”上尝试了网址,它返回了我需要的json。问题是 1.我将JSONObject更改为String并获取了该文件。这怎么可能。 我听说过Retrofit。我阅读了所有的文档,但我无法理解..根据使用Retrofit的人他们说Retrofit比AQuery更好。如何将此代码更改为Retrofit? 3.这是AQueryproblem还是我的代码问题

谢谢。

public class PastQuestionFragment extends Fragment {
AQuery aq = new AQuery(getActivity());
String postUrl = "http://192.168.0.21:3000/SendPastQuestion";

TextView pastQuestion;

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup 
container, Bundle savedInstanceState) {
    ViewGroup rootView = (ViewGroup) 
inflater.inflate(R.layout.fragment_pastquestion, container, false);
    pastQuestion = (TextView) rootView.findViewById(R.id.pastquestion);


    aq.ajax(postUrl, JSONObject.class, new AjaxCallback<JSONObject>() {
        @Override
        public void callback(String url, JSONObject json, AjaxStatus status) 
{
            if (json != null) {
                Log.d("debug", "json is not null");
                try {
                    pastQuestion.setText(json.getString("pastquestion"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.d("debug", "json is null");
            }
        }
    });
    return rootView;
}
}

1 个答案:

答案 0 :(得分:0)

您必须将此添加到 app build.gradle

compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile "com.squareup.retrofit2:converter-gson:2.3.0"

接下来创建一个 Webservice.class ,例如这样(你不需要授权令牌,只有你有一个令牌关联的电话)

public interface WebServices {

@GET("metadata/countries")
Call<List<Country>> getCountries(@Header("Authorization") String authorization);

@GET("metadata/states") ;; In your case should @POST("SendPastQuestion")
Call<List<State>> getStates(@Header("Authorization") String authorization);
}

然后您需要创建 Retrofit实例

Webservice service = new Retrofit.Builder()
            .baseUrl(Codes.V1.getDescription()) ;; In your case should be "http://192.168.0.21:3000/"
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(WebServices.class);

最后称之为

Response<List<State>> response = services.getStates("Bearer "+token).execute();

就应用架构而言,您可以按照Google指定的那样, https://developer.android.com/topic/libraries/architecture/guide.html

相关问题