你如何在json数组中解析json对象?

问题描述 投票:0回答:2

我对JSON很弱,可能有一个愚蠢的问题,并且想知道如何解析放置在JSON数组中的JSON对象。所以,截至目前,我有

public Single<Profile> doProfileApiCall() {
        return Rx2AndroidNetworking.post(ApiEndPoint.ENDPOINT_PROFILE)
                .addHeaders(mApiHeader.getProtectedApiHeader())
                .build()
                .getObjectSingle(Profile.class);

要检索我的个人资料参数,但在我的端点我有:

[{"Name": "this", "Email","[email protected]"}]

我的端点设置为:

 public static final String ENDPOINT_PROFILE =
            BuildConfig.BASE_URL
            + "/linktojson"; 

这给了我上面的JSON。但问题是[],我该如何修改:

 public Single<Profile> doProfileApiCall() {
            return Rx2AndroidNetworking.post(ApiEndPoint.ENDPOINT_PROFILE)
                    .addHeaders(mApiHeader.getProtectedApiHeader())
                    .build()
                    .getObjectSingle(Profile.class);

这样我就可以使用我的profile.java模型类了

public class Profile {
    @Expose
    @SerializedName("Name")
    private String name;
    @Expose
    @SerializedName("Email")
    private String email;
    etc...
}

知道如何去做吗?

android json rx-android android-json
2个回答
1
投票

在doProfileApiCall()方法而不是.getObjectSingle中使用

.getJSONArraySingle(ProfileList.class)

现在使用以下代码创建一个新类ProfileList.java。

List<Profile> profileList = new ArrayList<>();

public List<Profile> getProfileList() {
    return profileList;
}

public void setProfileList(List<Profile> profileList) {
    this.profileList = profileList;
}

将doProfileApiCall方法的返回类型更改为

public Single<ProfileList> doProfileApiCall()

每当您想要访问数据时,请使用列表位置0,以便将来获得更多数据时,可以相应地索引数据。


0
投票

一般来说,如果JSON根对象是array,你应该在List方面使用Java。在你的情况下你有array所以使用相关的方法:

return Rx2AndroidNetworking.post(ApiEndPoint.ENDPOINT_PROFILE)
          .addHeaders(mApiHeader.getProtectedApiHeader())
          .build()
          .getObjectListSingle(Profile.class);

Rx2ANRequest来源。

© www.soinside.com 2019 - 2024. All rights reserved.