如何使用 retrofit2 接收可变数量 类 的数据?

How to receive data that has an variable number of classes with retrofit2?

我正在构建一个 android 应用程序,但遇到以下问题:

使用 Retrofit2,到目前为止,我一直在通过创建响应和请求来发送 HTTP 请求 class。现在我需要发出一个请求,该请求将 return 数据具有未指定的可变数量 classes。当我不知道要发送多少数据时如何创建响应 class 以及当我不知道可以发送多少 textview 时如何将该数据打包到应用程序 textview 中?

"data": {

    "mData": [
        {
            "Field1": 262,
            "Field2": 6695,
        },
        {
            "Field1": 252,
            "Field2": 3295,
        }
             ]
},
"errors": false}

正如我在评论中分享的细节以及当您确认示例响应时,您实际上没有收到 "unspecified variable number of classes" 的响应,但响应实际上对 JSON 数组具有相同的键集和 JSON 个对象。例如"data"、"mData"、"Field1"、"Field2"等

现在要回答您的问题,您只需获取 "mData" JSON 数组并遍历每个 JSON 对象。

关于动态添加视图,每个视图都有可用的包装器 类,例如 TextView、Button 等。要动态创建和添加视图,您可以创建和对象,如:

LinearLayout parentLayout = (LinearLayout)findViewById(R.id.layout);

LayoutInflater layoutInflater = getLayoutInflater();
View view;

for (int i = 1; i < jsonObjctsCount; i++){
    // Add the text layout to the parent layout
    view = layoutInflater.inflate(R.layout.text_layout, parentLayout, false);

    // In order to get the view we have to use the new view with text_layout in it
    TextView textView = (TextView)view.findViewById(R.id.text);
    textView.setText("Row " + i);

    // Add the text view to the parent layout
    parentLayout.addView(textView);
}