有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java:可以创建一个带有“变量”字段的类吗?

谢谢你的帮助

我有以下情况:

我有一个包含API响应的类:

public class EventsResponse extends ApiResponse {

  public JSONArray response;

  public EventsResponse(Boolean success,RequestHandle requesthandle, JSONArray responsefromapi) {
    super(success, requesthandle);
    if(responsefromapi!=null)this.response=responsefromapi;
    else response=null;
  }
  public EventsResponse(Boolean success,RequestHandle requesthandle, JSONObject responsefromapi) {
    super(success, requesthandle);
    if(responsefromapi!=null)this.response=responsefromapi;
    else response=null;
  }
}

正如你所看到的,这里有些东西不起作用:

如果responsefromapi是一个JSONObject我试着把它分配给一个response这是一个JSONArray显然不起作用

我想做的是:

responsefromapi分配给response,并根据responsefromapi的内容将response指定为JSONObjectJSONArray

因此,我可以使用一个单格类EventsResponse来处理这两种情况,并且EventsResponse将包含一个response,它是JSONObjectJSONArray,具体取决于情况

请问这可能吗

谢谢


共 (3) 个答案

  1. # 1 楼答案

    @LisaAnne。我的理解如下:

    1. 您有两个场景,其中一个将返回JsonArray类型,另一个将返回JSONObject类型
    2. 为了确保实现是干净的,并且是在同一个类中编写的,您已经创建了两个重载构造函数,以从调用此EventsResponse类的类中获取响应类型
    3. 然而,问题似乎在于将responseFromApi(JSONObject或JSONArray,具体取决于使用的构造函数)分配给JSONArray响应属性,因为不存在从对象到JSONArray的直接转换

    详细信息:-
    根据我的理解,我们使用JSONObject来存储和传递JSON字符串的值,比如{name:"LisaAnne", address:"xyz", responseArray:[{name1:"n1"},{name1:"n2"}]}. JSONObject包含键值对,而, JSONArray包含一个有序对。如果将responseArray的值提取到JSONArray类型的对象中,您将成功

    要从响应中获取数组,应使用以下类型的语句

    JSONArray response= bigDataResponse.getJSONArray("responseArray");
    

    因此,从JSONObject到JSONArray的直接强制转换是不可能的。您必须获取包含数组的密钥,并使用上面给出的语句来获取它

    如果你能给我在JSONObject responsefromapiJSONArray responsefromapi中收到的响应结构,我就能给你一个更好的解决方案

    希望这有帮助

  2. # 2 楼答案

    不是很优雅,但您可以尝试使用Object公共超类来引用您的响应:

    public Object response;
    ...
    ...
    public EventsResponse(Boolean success,RequestHandle requesthandle, JSONArray responsefromapi) {
        super(success, requesthandle);
        if(response!=null)this.response= (Object)responsefromapi;
        else response=null;
    }
    

    稍后在代码中使用引用的对象需要Java的反射:

    if(response.getClass().equals(JSONArray.class)) {
      ...
      ...
      JSONArray responseAsJSONArray = (JSONArray)response;
      ...
    } 
    
  3. # 3 楼答案

    尝试使用泛型:

    public class EventsResponse<K> extends ApiResponse {
        public K response;
        public EventsResponse(Boolean success, RequestHandle requesthandle, K responsefromapi) {
            super(success, requesthandle);
            response = responsefromapi;
        }
    }
    

    你可以这样称呼它:

    new EventResponse<JSONObject>(...);
    

    new EventResponse<JSONArray>(...);