Android에서 GSON 또는 다른 라이브러리를 사용하지 않고 개조를 사용하여 문자열로 응답을 얻는 방법
이 질문에 이미 답변이 있습니다.
- 클래스 예제에 대한 통화 어댑터를 만들 수 없습니다 .Simple 12 Answers
다음 API에서 응답을 얻으려고합니다.
https://api.github.com/users/username
하지만을 String
사용하여 String
.NET을 구문 분석하고 가져올 수 있도록 응답을 얻는 방법을 모르겠습니다 JSONObject
.
사용 된 개조 버전 :
개조 : 2.0.0-beta1
나는 지금까지 이것을 시도했다 :
public interface GitHubService {
@GET("/users/{user}")
public String listRepos(@Path("user") String user,Callback<String> callback);
}
검색 :
GitHubService service = retrofit.create(GitHubService.class);
service.listRepos("username", new Callback<String>() {
@Override
public void onResponse(Response response) {
System.out.println(response.toString());
}
@Override
public void onFailure(Throwable t) {
}
});
예외:
Caused by: java.lang.IllegalArgumentException: Could not locate call adapter for class java.lang.String. Tried:
* retrofit.ExecutorCallAdapterFactory
at retrofit.Utils.resolveCallAdapter(Utils.java:67)
at retrofit.MethodHandler.createCallAdapter(MethodHandler.java:49)
어떤 도움이라도 정말 감사하겠습니다.
** 업데이트 ** String
아래의 원래 답변보다 덜 의식적인 응답 을 허용하는 스칼라 변환기가 개조에 추가되었습니다 .
예제 인터페이스-
public interface GitHubService {
@GET("/users/{user}")
Call<String> listRepos(@Path("user") String user);
}
ScalarsConverterFactory
개조 빌더에을 추가하십시오 . 참고 :ScalarsConverterFactory
및 다른 팩토리를 사용하는 경우 먼저 스칼라 팩토리를 추가하십시오.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
// add other factories here, if needed.
.build();
gradle 파일에 스칼라 변환기도 포함해야합니다.
implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'
--- 원래 답변 (여전히 작동하며 더 많은 코드) ---
I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject
land. I suspect your specific problem might be better solved using a custom gson TypeAdapter
or a retrofit Converter
if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -
First, if you are using Retrofit 2, you should start using the Call
API. Instead of sending an object to convert as the type parameter, use ResponseBody
from okhttp --
public interface GitHubService {
@GET("/users/{user}")
Call<ResponseBody> listRepos(@Path("user") String user);
}
then you can create and execute your call --
GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Response<ResponseBody> response) {
try {
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Throwable t) {
e.printStackTrace();
}
});
Note The code above calls string()
on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream()
instead. See the ResponseBody
docs.
'Programing' 카테고리의 다른 글
NSString에서 문자를 제거 하시겠습니까? (0) | 2020.08.27 |
---|---|
sqlite 쿼리에서 dict를 어떻게 얻을 수 있습니까? (0) | 2020.08.26 |
IEnumerator와 IEnumerable의 차이점은 무엇입니까? (0) | 2020.08.26 |
Windows의 Cygwin에서 crontab을 어떻게 실행합니까? (0) | 2020.08.26 |
C # 제네릭 오류에 대한 도움말- " 'T'형식은 nullable이 아닌 값 형식이어야합니다." (0) | 2020.08.26 |