我正在尝试使用Retrofit构建一个Muzei扩展,就像他在他的例子中使用的示例一样。
我无法真正理解Retrofit,不过这就是我所拥有的
ArtSource.java
public class ArtSource extends RemoteMuzeiArtSource {
private static final String TAG = "The Muzei Collection";
private static final String SOURCE_NAME = "The Muzei Collection";
private static final int ROTATE_TIME_MILLIS = 3 * 60 * 60 * 1000; // rotate every 3 hours
public ArtSource() {
super(SOURCE_NAME);
}
@Override
public void onCreate() {
super.onCreate();
setUserCommands(BUILTIN_COMMAND_ID_NEXT_ARTWORK);
}
@Override
protected void onTryUpdate(int reason) throws RetryException {
String currentToken = (getCurrentArtwork() != null) ? getCurrentArtwork().getToken() : null;
RestAdapter restAdapter = new RestAdapter.Builder()
.setServer("http://elliothesp.co.uk")
.build();
ArtService service = restAdapter.create(ArtService.class);
PhotosResponse response = service.getPopularPhotos();
if (response == null || response.photos == null) {
throw new RetryException();
}
if (response.photos.size() == 0) {
Log.w(TAG, "No photos returned from API.");
scheduleUpdate(System.currentTimeMillis() + ROTATE_TIME_MILLIS);
return;
}
Random random = new Random();
Photo photo;
String token;
while (true) {
photo = response.photos.get(random.nextInt(response.photos.size()));
token = Integer.toString(photo.id);
if (response.photos.size() <= 1 || !TextUtils.equals(token, currentToken)) {
break;
}
}
publishArtwork(new Artwork.Builder()
.title(photo.title)
.byline(photo.user)
.imageUri(Uri.parse(photo.url))
.token(token)
.viewIntent(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.google.com")))
.build());
scheduleUpdate(System.currentTimeMillis() + ROTATE_TIME_MILLIS);
}
}
ArtService.java
interface ArtService {
@GET("/muzei.php")
PhotosResponse getPopularPhotos();
static class PhotosResponse {
List<Photo> photos;
}
static class Photo {
int id;
String user;
String title;
String url;
}
}
基本上,我正在尝试从http://elliothesp.co.uk/muzei.php获取JSON并将每个项目传递给publishArtwork。它运行异常,因为它无法从JSON提要中找到任何照片,我不知道如何使其正常工作
答案 0 :(得分:4)
JSON
格式response
不适合您的界面,应该是:
interface service {
@GET("/muzei.php")
Map<String,Photo> getPopularPhotos();
static class Photo {
int id;
String user;
String title;
String url;
}
}
response
:
Map<String, Photo> response = service.getPopularPhotos();
然后在获得response
迭代后重新编写代码