2017-08-26 22 views
0

这是我尝试使用的完整代码片段。我使用AQuery来获取json。但我有一个问题。 JsonObject,JsonObject ...始终为空。我尝试了“邮递员”的URL,它返回了我需要的JSON。问题是 1.我将JSONObject改为String,并且得到了该文件。这怎么可能。 2.我听说过Retrofit。我阅读所有的文档,但我不明白..根据谁使用改造他们说改造比AQuery更好。我如何将此代码更改为Retrofit? 3.它是AQueryproblem或我的代码的问题AQuery JSONObject null

谢谢。

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

回答

0

你必须把它添加到您的应用的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); 
} 

然后你需要创建一个改造实例

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

在应用架构方面,你可以按照由谷歌所指示的一个, https://developer.android.com/topic/libraries/architecture/guide.html